Difficulty:: Medium
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
1 2 3 4 5 6 7 8 9 10
| Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
|
Solution
Language: Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null) { return result; } Arrays.sort(nums); dfsHelper(nums, result, new ArrayList<Integer>(), 0); return result; } private void dfsHelper(int[] nums, List<List<Integer>> result, List<Integer> subset, int index) { result.add(new ArrayList<Integer>(subset)); for (int i = index; i < nums.length; i++) { if (i != index && nums[i] == nums[i - 1]) { continue; } subset.add(nums[i]); dfsHelper(nums, result, subset, i + 1); subset.remove(subset.size() - 1); } } }
|