90. Subsets II
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Backtracking
- Time
- O(2^N * N)
- Space
- O(2^N * N)
Standard Solution (C++)
SummaryGiven an integer array that may contain duplicates, find all unique subsets (the power set) and return them without any duplicate subsets.
Approach
- Sort the input so duplicate values are adjacent, making it easy to detect and skip them.
- Use backtracking: at each index, make a binary choice — include the current element (recurse to the next index) or skip it.
- When skipping, advance past all consecutive copies of the current value so the same element is never used as the "skip" branch more than once at the same decision level.
- This guarantees every unique subset is generated exactly once without a hash-set or post-filtering step.
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
void backtrack(const vector<int>& nums, int idx, vector<int>& cur, vector<vector<int>>& res) {
if (idx == (int)nums.size()) {
res.push_back(cur);
return;
}
// Choice 1: include nums[idx]
cur.push_back(nums[idx]);
backtrack(nums, idx + 1, cur, res);
cur.pop_back();
// Choice 2: skip nums[idx] (and every duplicate of it at this level)
int next = idx + 1;
while (next < (int)nums.size() && nums[next] == nums[idx])
++next;
backtrack(nums, next, cur, res);
}
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> cur;
backtrack(nums, 0, cur, res);
return res;
}
};
Time O(2^n * n) Space O(2^n * n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
class Solution {
public:
void dfs(vector<vector<int>>& res, const vector<int>& nums, vector<int>& cur, int idx) {
if(idx==nums.size()){
res.push_back(cur);
return;
}
cur.push_back(nums[idx]);
dfs(res, nums, cur, idx+1);
cur.pop_back();
int next=idx+1;
while(next<nums.size() && nums[next]==nums[idx]){
++next;
}
dfs(res, nums, cur, next);
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> res;
vector<int> cur;
std::sort(nums.begin(), nums.end());
dfs(res, nums, cur, 0);
return res;
}
};
// Time Complexity: O(2^N * N).
// Space Complexity: O(2^N * N) for the result, O(N) for the auxiliary space. Time O(2^N * N) Space O(2^N * N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.