Created
June 4, 2020 01:13
-
-
Save bhaveshmunot1/3f5f31f2d9b1a9facee93608c06d24a7 to your computer and use it in GitHub Desktop.
Leetcode #78: Subsets
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 { | |
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