Skip to content

Instantly share code, notes, and snippets.

@stellaqx
Last active October 8, 2021 05:47
Show Gist options
  • Save stellaqx/b9c04daa24de72ad86afe0c679155388 to your computer and use it in GitHub Desktop.
Save stellaqx/b9c04daa24de72ad86afe0c679155388 to your computer and use it in GitHub Desktop.
Subsets (C++)
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