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 Solution { public ArrayList<ArrayList<Integer>> subsets(int[] S) { Arrays.sort(S); ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>(); if(S==null) { return ret; } ret.add(new ArrayList<Integer>()); for(int i=0;i<S.length;i++) { int s = S[i]; ArrayList<ArrayList<Integer>> add = new ArrayList<ArrayList<Integer>>(); for(ArrayList<Integer> lst : ret) { ArrayList<Integer> lst2 = new ArrayList<Integer>(lst); lst2.add(s); add.add(lst2); } ret.addAll(add); } return ret; } }
========
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> ret = new ArrayList<List<Integer>>(); if (nums == null || nums.length == 0) { return ret; } Arrays.sort(nums); List<Integer> empty = new ArrayList<Integer>(); ret.add(empty); for (int i = 0; i < nums.length; i++) { int n = nums[i]; int count = ret.size(); for (int j = 0; j < count; j++) { List<Integer> newList = new ArrayList<Integer>(ret.get(j)); newList.add(n); ret.add(newList); } } return ret; } }
没有评论:
发表评论