π Problem Details
- Title:
90 Subsets II
- Link: https://leetcode.com/problems/subsets-ii/
- Difficulty: Medium
- Tags/Categories: Backtracking
input array
nums
can contain duplicates return all possible subsets (powerset) most not contain duplicate sets
πWhat Were My Initial Thoughts?
- difference between the original subsets problem and this problem is that the input array can contain duplicates
- how do we manage duplicates when generating unique subsets?
- by sorting the input array first, we can check the previous element to see if we've already processed that number
π‘ Explanation of Solution
- sort the input array
- create a DFS function that has the function signature:
- nums
- vector<vector<int>> result
- vector<int> curr
- int index
- push the current vector into result (as each recursive call is a valid subset)
- iterate over nums, either choose to include or exclude the current element, reducing the index by 1 each recursive call
- if the previous element is the same as the current, then continue / skip
- push the current element into curr
- recrusively call dfs , incrementing index by 1
- undo the last choice (pop from curr)
β Complexity Analysis
Time Complexity: O(2^n)
Space Complexity: O(2^n)
π» Implementation of Solution
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
vector<vector<int>> result;
vector<int> current;
sort(nums.begin(), nums.end());
dfs(nums, 0, current, result);
return result;
}
void dfs(vector<int>& nums, int index, vector<int>& current, vector<vector<int>>& result) {
// add the current subset to the result
result.push_back(current);
// explore further by including each remaining element
for(int i = index; i < nums.size(); i++) {
// skip duplicates
if(i > index && nums[i] == nums[i - 1]) continue;
// choose
current.push_back(nums[i]);
// explore
dfs(nums, i + 1, current, result);
// backtack (undo the choice)
current.pop_back();
}
}
};