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:
1 2 3 4 5 6 7 8 9 10 11 12 |
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] |
Implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public static List<List<Integer>> subsets(int[] nums) { List<List<Integer>> mset = new ArrayList<List<Integer>>(); mset.add(new ArrayList<Integer>()); Arrays.sort(nums); for(int i = 0; i < nums.length; i++) { int size = mset.size(); for(int m = 0; m < size; m++) { List<Integer> tmp = mset.get(m); if(!tmp.contains(nums[i])) { List<Integer> tmp2 = new ArrayList<Integer>(tmp); tmp2.add(nums[i]); if(!mset.contains(tmp2)) { mset.add(tmp2); } } } } return mset; } |