Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode #78: Subsets
class Solution {
vector<vector<int>> answer;
vector<int> numbers;
void recurse(vector<int> path, int startIndex) {
// All paths are of course the subsets of given set because we are
// choosing the elements from the given numbers.
answer.push_back(path); // add current subset into answer.
for (int i=startIndex; i<numbers.size(); i++) { // for each possibility.
path.push_back(numbers[i]); // consider this possibility.
recurse(path, i+1); // to avoid choosing same number multiple
// times, move the startIndex by 1.
path.pop_back(); // undo the considered possibility.
}
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
numbers = nums;
vector<int> path; // to store the subset. Initially empty.
recurse(path,
0); // what index to start from.
return answer;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment