Skip to main content

Subsets

Problem

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.

Solution Approach

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

Click - to see solution code
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
set<vector<int>> st;
for (int i = 0; i < (1ll << nums.size()); i++) {
vector<int> subset;
for (int j = 0; j < nums.size(); j++) {
int bit = (1ll << j) & i;
if (bit) subset.push_back(nums[j]);
}
sort(subset.begin(), subset.end());
st.insert(subset);
}
vector<vector<int>> ans(st.begin(), st.end());
return ans;
}
};