Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
主题思想: 这个和77 题同样是通过回溯完成的,形成了一个比较典型的方法吧
AC 代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ans=new ArrayList<List<Integer>>();
Arrays.sort(nums);
dfs(nums,ans,new ArrayList<Integer>(),0);
return ans;
}
public void dfs(int[] nums,List<List<Integer>>ans,List<Integer> tmp,int start){
ans.add(new ArrayList<Integer>(tmp));
for(int i=start;i<nums.length;i++){
tmp.add(nums[i]);
dfs(nums,ans,tmp,i+1);
tmp.remove(tmp.size()-1);
}
}
}