Skip to main content

Subsets II

Problem

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

Solution Approach

Iterate overall possible subset. This can be done using recursion or bitmasking.

Expected Time complexity: O(2n)O(2^n)

Click - to see solution code
class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
int n = nums.size();
int end = pow(2, n);

set<vector<int>> store;
for (int i = 0; i < end; i++) {
vector<int> arr;
for (int j = 0; j < n; j++) {
int bit = (1 << j) & i;
if (bit) arr.push_back(nums[j]);
}
sort(arr.begin(), arr.end());
store.insert(arr);
}
vector<vector<int>> ans;
for (auto i : store) ans.push_back(i);
return ans;
}
};