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:
Click - to see solution code
- C++
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;
}
};