Subsets


Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

1
2
3
4
5
6
7
8
9
10
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Arrays.sort(nums);
backTrack(res,new ArrayList<Integer>(), nums, 0);
return res;
}
public void backTrack(List<List<Integer>> res, List<Integer> subset, int[] nums, int start){
res.add(new ArrayList<Integer>(subset));
for(int i=start; i<nums.length; i++) {
subset.add(nums[i]);
backTrack(res, subset, nums, i+1);
subset.remove(subset.size()-1);
}
}
}