题干:
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
public class 子集 {
public static void main(String[] args) {
int[] nums = {1,2,3};
List<List<Integer>> res = subsets(nums);
for (List<Integer> list : res) {
System.out.println(list);
}
}
public static List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
dfs(0,nums,res,new ArrayList<>());
return res;
}
public static void dfs(int index,int[]nums,List<List<Integer>> res,List<Integer> temp){
res.add(new ArrayList<>(temp));
for(int i=index;i< nums.length;i++){
temp.add(nums[i]);
dfs(i+1,nums,res,temp);
temp.remove(temp.size()-1);
}
}
}
这题考虑的算法是回溯,每次从index开始进行遍历,遍历后忽略掉该数字再往后进行遍历。具体参考下图的递归树。
每次递归开启时,以参数列表中的temp为模板创建一个新链表并添加到res中,意思就是将上一层递归的结果进行保存。而参数列表中的temp从始至终都是同一个链表,所以在进行回溯的过程中需要删除之前递归时新添加的元素。
同时,我们可以发现递归树中没有重复部分,所以不需要剪枝。