示例 1:
示例 2:
void backTracking(参数)
{
if(终止条件)
{
保存结果;
return;
}
for(遍历从当前位置出发的所有“路径”)
{
保存“路径”节点;
backTracking(所需参数);
回溯处理,删除上一步保存的“路径”节点,准备进行新的递归
}
}
package Array;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: IronmanJay
* @Description: 78.子集
* @CreateTime: 2022-11-24 09:02
*/
public class p78_Subsets {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> res = subsets(nums);
System.out.println("res = " + res);
}
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs_back(0, nums, res, path);
return res;
}
public static void dfs_back(int start, int[] nums, List<List<Integer>> res, List<Integer> path) {
res.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
path.add(nums[i]);
dfs_back(i + 1, nums, res, path);
path.remove(path.size() - 1);
}
}
}
#include
#include
void dfs_back(int* nums, int numsSize, int** res, int* returnSize, int** returnColumnSizes, int start, int* path, int pathSize)
{
res[*returnSize] = (int*)malloc(sizeof(int) * pathSize);
memcpy(res[*returnSize], path, sizeof(int) * pathSize);
(*returnColumnSizes)[*returnSize] = pathSize;
(*returnSize)++;
for (int i = start; i < numsSize; i++)
{
path[pathSize++] = nums[i];
dfs_back(nums, numsSize, res, returnSize, returnColumnSizes, i + 1, path, pathSize);
pathSize--;
}
}
int** subsets(int* nums, int numsSize, int* returnSize, int** returnColumnSizes)
{
*returnSize = 0;
*returnColumnSizes = (int*)malloc(sizeof(int) * 10001);
int** res = (int**)malloc(sizeof(int*) * 10001);
int* path = (int*)malloc(sizeof(int) * numsSize);
dfs_back(nums, numsSize, res, returnSize, returnColumnSizes, 0, path, 0);
return res;
}
/*主函数省略*/
Java语言版
C语言版