78.子集
- 子集
難度中等549
給定一組不含重複元素的整數數組 nums,返回該數組所有可能的子集(冪集)。
說明:解集不能包含重複的子集。
示例:
輸入: nums = [1,2,3] 輸出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
回溯
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
//1.終止條件
if(nums == null) return result;
//2.遞歸
dfs(result,nums,new ArrayList<>(),0);
return result;
}
//回溯算法
private void dfs(List<List<Integer>> result,int [] nums,List<Integer> subResult,int index){
//1.終止條件
if(index == nums.length){
result.add(new ArrayList<Integer>(subResult));
return;
}
//2.not pick the number at this index
dfs(result,nums,subResult,index+1);
//3.add
subResult.add(nums[index]);
//4. pick the number at this index
dfs(result,nums,subResult,index+1);
//5.撤銷
subResult.remove(subResult.size()-1);
}