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:
Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2], [] ]
子集II。
题意跟78题几乎一样,唯一多一个条件是input里面有重复元素,但是请不要重复输出相同的子集。思路还是回溯,套用78题的模板。注意这个题是需要对input排序的,在helper函数中,需要skip相同元素。
时间O(nlogn) - 因为sort了input + O(2^n) = O(2^n)
空间O(n)
Java实现
1 class Solution { 2 public List<List<Integer>> subsetsWithDup(int[] nums) { 3 List<List<Integer>> res = new ArrayList<>(); 4 // corner case 5 if (nums == null || nums.length == 0) { 6 return res; 7 } 8 Arrays.sort(nums); 9 helper(res, new ArrayList<>(), nums, 0); 10 return res; 11 } 12 13 private void helper(List<List<Integer>> res, List<Integer> list, int[] nums, int start) { 14 res.add(new ArrayList<>(list)); 15 for (int i = start; i < nums.length; i++) { 16 if (i != start && nums[i] == nums[i - 1]) 17 continue; 18 list.add(nums[i]); 19 helper(res, list, nums, i + 1); 20 list.remove(list.size() - 1); 21 } 22 } 23 }