LeetCode - Subsets II

less than 1 minute read

Problem description

description

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],
  []
]

Analysis

The idea is to skip other duplicates after the backtrack. So that we can consider the subsets only once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        
        Arrays.sort(nums);
        
        backtrack(res, new ArrayList<>(), 0, nums);
        
        return res;
    }
    
    void backtrack(List<List<Integer>> res, List<Integer> list, int start, int[] nums){
        res.add(new ArrayList<>(list));
        
        if (start == nums.length){
            return;
        }
        
        for (int i = start; i< nums.length; i++){
            
            
            list.add(nums[i]);
            backtrack(res, list, i+1, nums);
            list.remove(list.size() - 1);
            
            while(i + 1 < nums.length && nums[i] == nums[i + 1]){
                i++;
            }
        }
    }
}

What to improve

  • skip duplicates must be after the backtrack so that we can use previous information.