Last active
October 8, 2021 05:47
-
-
Save stellaqx/b9c04daa24de72ad86afe0c679155388 to your computer and use it in GitHub Desktop.
Subsets (C++)
This file contains 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
class Solution { | |
public: | |
/** | |
* @param nums: A set of numbers | |
* @return: A list of lists | |
*/ | |
vector<vector<int>> subsets(vector<int> &nums) { | |
if (nums.size() == 0) { | |
vector<vector<int>> res; | |
vector<int> empty; | |
res.push_back(empty); | |
return res; | |
//return {{}}; // empty vector | |
} | |
// sort | |
std::sort(nums.begin(), nums.end()); | |
// problem: n-1 | |
vector<int> sub = nums; | |
sub.erase(sub.end() - 1); | |
vector<vector<int>> subs = subsets(sub); | |
// problem: n | |
vector<vector<int>> res = subs; | |
for (auto& s: subs) { | |
s.push_back(nums[nums.size() - 1]); | |
res.push_back(s); | |
} | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment