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], [] ]
public class Subsets { public List<List<Integer>> subsets(int[] S) { if (S == null) return null; Arrays.sort(S); List<List<Integer>> list = new ArrayList<List<Integer>>(); list.add(new ArrayList<Integer>()); for (int s : S) helper(list, s); return list; } public void helper(List<List<Integer>> lists, int val) { for (int i = 0; i < lists.size(); i++) { List<Integer> tmp = new ArrayList<Integer>(lists.get(i)); tmp.add(val); lists.add(tmp); } } }
时间: 2024-10-06 07:37:53