Subsets II
Medium
Topics
Given an integer array nums that may contain duplicates, return all possible unique subsets. The result may be in any order.
Example 1
Duplicates in the input would otherwise produce the same subset twice. Sorting first puts equal values together, and then the rule is to skip a value whose equal predecessor was not taken at this level — which keeps each distinct subset exactly once. 6 here, not 8.
Each chip is one distinct subset.
Input: nums = [1,2,2] Output: [[],[1],[2],[1,2],[2,2],[1,2,2]]
Example 2
Input: nums = [0] Output: [[],[0]]
Constraints
- 1 <= nums.length <= 10
- -10 <= nums[i] <= 10
Editorial — intuition, approach, complexity and pitfalls
Intuition
Duplicates cause repeated subsets. Sort first so equal values are adjacent, then at each recursion level skip a value identical to the previous choice at that same level.
Approach
- Sort nums.
- DFS recording each partial subset; iterate candidates from start.
- Skip
nums[i] == nums[i-1]wheni > startto avoid duplicate subsets.
Dry Run
nums = [1, 2, 2] (already sorted; sorting is what puts equal values adjacent)
emit [] loop i from 0
emit [1] loop i from 1
emit [1, 2] loop i from 2
emit [1, 2, 2]
i=2: nums[2] == nums[1] and i > start -> skip
emit [2] loop i from 2
emit [2, 2]
i=2: nums[2] == nums[1] and i > start -> skip
answer [] | [1] | [1,2] | [1,2,2] | [2] | [2,2]
The condition is `i > start`, and the two skips in the trace show why. At the
outer level start is 0, so i=2 is skipped -- choosing the second 2 as the FIRST
element would re-generate everything the first 2 already produced. But inside the
[2] branch start is 2, so i=2 is NOT skipped, and [2,2] is generated: using a
duplicate value again at a deeper position is a genuinely different subset.
Change it to `i > 0` and the skip stops being position-aware. Every repeated
value is refused everywhere, and the output collapses to
[] [1] [1,2] [2] -- both [1,2,2] and [2,2] disappear.
So the rule is "do not start a new branch with a value already tried at this
level", not "never repeat a value".Complexity
- Time — O(n * 2^n): up to 2^n subsets copied in O(n).
- Space — O(n): recursion depth.
Common Pitfalls
- Skip only when i > start; skipping at i == start would drop valid subsets.
Full Solution — all languages
class Solution:
def subsetsWithDup(self, nums):
nums.sort()
res=[]
def dfs(start,path):
res.append(path[:])
for i in range(start,len(nums)):
if i>start and nums[i]==nums[i-1]: continue
path.append(nums[i]); dfs(i+1,path); path.pop()
dfs(0,[])
return resimport java.util.*;
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> res=new ArrayList<>();
dfs(nums,0,new ArrayList<>(),res);
return res;
}
void dfs(int[] nums,int start,List<Integer> path,List<List<Integer>> res) {
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++) {
if(i>start&&nums[i]==nums[i-1])continue;
path.add(nums[i]);
dfs(nums,i+1,path,res);
path.remove(path.size()-1);
}
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(),nums.end());
vector<vector<int>> res;
vector<int> path;
function<void(int)> dfs=[&](int start) {
res.push_back(path);
for(int i=start;i<(int)nums.size();i++) {
if(i>start&&nums[i]==nums[i-1])continue;
path.push_back(nums[i]);
dfs(i+1);
path.pop_back();
}
};
dfs(0);
return res;
}
};/**
* @param {number[]} nums
* @return {number[][]}
*/ var subsetsWithDup = function(nums) {
nums.sort((a,b)=>a-b);
const res=[];
function dfs(start,path) {
res.push(path.slice());
for(let i=start;i<nums.length;i++) {
if(i>start&&nums[i]===nums[i-1])continue;
path.push(nums[i]);
dfs(i+1,path);
path.pop();
}
}
dfs(0,[]);
return res;
};