Given a set of distinct integers, nums, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- 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],
[]
]
解题思路:
和上题十分相似,修改上题代码即可,JAVA实现如下:
static public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add(new ArrayList<Integer>());
Arrays.sort(nums);
for(int i=1;i<=nums.length;i++)
dfs(list, nums.length, i, 0,nums,-1);
return list;
} static List<Integer> alist = new ArrayList<Integer>(); static void dfs(List<List<Integer>> list, int n, int k, int depth,int[] nums,int last) {
if (depth >= k) {
list.add(new ArrayList<Integer>(alist));
return;
}
for (int i = last+1; i <= n-k+depth; i++) {
alist.add(nums[i]);
dfs(list, n, k, depth + 1,nums,i);
alist.remove(alist.size() - 1);
}
}