子集
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
提示:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
nums 中的所有元素 互不相同
解法:回溯
从前往后遍历,遇到一个数就把所有子集加上该数组成新的子集,遍历完毕即是所有子集
> ************回溯模板**********
> result = [] def backtrack(路径, 选择列表):
> if 满足结束条件:
> result.add(路径)
> return
> for 选择 in 选择列表:
> 做选择
> backtrack(路径, 选择列表)
> 撤销选择
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
List<Integer> path=new ArrayList<>();
dfs(res,path,nums,0);
return res;
}
public void dfs(List<List<Integer>> res,List<Integer> path,int[] nums,int start){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
path.add(nums[i]);
dfs(res,path,nums,i+1);
path.remove(path.size()-1);
}
}
}
子集 II
给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。 解集 不能包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
解法:回溯
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res=new ArrayList<>();
List<Integer> path=new ArrayList<>();
dfs(res,path,nums,0);
return res;
}
public void dfs(List<List<Integer>> res,List<Integer> path,int[] nums,int start){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
if(i>start&&nums[i]==nums[i-1]){
continue;
}
path.add(nums[i]);
dfs(res,path,nums,i+1);
path.remove(path.size()-1);
}
}
}