Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
class Solution
{
public:
vector<vector<int>> subsets(vector<int> &nums)
{
int n = nums.size();
vector<vector<int>> sets;
for (int i = 0; i < (1 << n); i++) //All bits from 0 to n-1, (if u left shift 1 by n, it will give 2^n)
{
vector<int> sset;
for (int j = 0; j < n; j++) //Check each bit of i
{
if ((i >> j) & 1) //If jth bit of i is set, then include nums[j] in the current subset, (if you right shift i by j and check if the last bit is set with & 1 and if it results in 1, then the jth bit is set else it is not set)
{
sset.push_back(nums[j]);
}
}
sets.push_back(sset);
}
return sets;
}
};
Given an integer array nums that may contain duplicates, return all possible subsets (the power set).
class Solution
{
public:
vector<vector<int>> subsetsWithDup(vector<int> &nums)
{
int n = nums.size();
vector<vector<int>> ans;
sort(nums.begin(), nums.end());
for (int i = 0; i < (1 << n); i++)
{
vector<int> subset;
bool valid = true;
for (int j = 0; j < n; j++)
{
if ((i >> j) & 1)
{
if (j > 0 && nums[j] == nums[j - 1] && ((i >> (j - 1)) & 1) == 0) //check if previous element is same and not included i.e, the previous bit is not set
{
valid = false;
break;
}
subset.push_back(nums[j]);
}
}
if (valid)
ans.push_back(subset);
}
return ans;
}
};