Created
July 7, 2020 04:06
-
-
Save Irene-123/5aa60495b3cacaf786583ceb4e51c19a to your computer and use it in GitHub Desktop.
Subsets Leetcode C++ solution
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ITERATIVE SOLUTION | |
``` | |
class Solution { | |
public: | |
vector<vector<int>> subsets(vector<int>& nums) { | |
vector< vector <int> > res(1,vector<int>()); | |
sort(nums.begin(),nums.end()); | |
for (int i=0;i<int(nums.size());i++){ | |
int n=res.size(); | |
for (int j=0;j<n;j++){ | |
res.push_back(res[j]); | |
res.back().push_back(nums[i]); | |
} | |
} | |
return res; | |
} | |
}; | |
``` | |
Bit-manipulation | |
``` | |
class Solution { | |
public: | |
vector<vector<int>> subsets(vector<int>& nums) { | |
int n=nums.size(); | |
int p=1<<n; | |
vector <vector <int>> res(p); | |
for (int i=0;i<p;i++){ | |
for (int j=0;j<n;j++){ | |
if ((i>>j)& 1){ | |
res[i].push_back(nums[j]); | |
} | |
} | |
} | |
return res; | |
} | |
}; | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment