Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created June 4, 2020 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/3f5f31f2d9b1a9facee93608c06d24a7 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/3f5f31f2d9b1a9facee93608c06d24a7 to your computer and use it in GitHub Desktop.
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