给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
思路: 回溯法即可,注意递归到下一层是i+1.
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
if (nums == null || nums.length == 0)
return list;
dfs(list,new ArrayList<Integer>(),0,nums);
return list;
}
public void dfs(List<List<Integer>> list,List<Integer> tmp,int start,int[] nums) {
list.add(new ArrayList<Integer>(tmp));
for (int i = start;i < nums.length;i++) {
tmp.add(nums[i]);
dfs(list,tmp,i+1,nums);
tmp.remove(tmp.size()-1);
}
}
}