Given a set of distinct integers, S, 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 S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Solution:
1 public class Subsets { 2 public List<List<Integer>> subsets(int[] S) { 3 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 4 List<Integer> path = new ArrayList<Integer>(); 5 6 Arrays.sort(S); 7 8 subsets(S, path, ret, 0); 9 10 return ret; 11 } 12 13 public void subsets(int[] S, List<Integer> path, List<List<Integer>> ret, int index) { 14 // 把当前的结果可以添加到结果集中. 空集也算是一种集合 15 ret.add(new ArrayList<Integer>(path)); 16 17 for (int i = index; i < S.length; i++) { 18 path.add(S[i]); 19 20 // 注意!这里的index要填写i + 1,而不是index,开始老是会犯错。 21 subsets(S, path, ret, i + 1); 22 path.remove(path.size() - 1); 23 } 24 } 25 }