Created
June 4, 2020 01:12
-
-
Save bhaveshmunot1/1b6a2a13ab12ab317cb609c2eef77423 to your computer and use it in GitHub Desktop.
Leetcode #46: Permutations
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) { | |
if (path.size() == numbers.size()) { // all numbers are added. | |
answer.push_back(path); // add current permutation into answer. | |
} | |
for (int i=0; i<numbers.size(); i++) { // for each possibility. | |
if (find(path.begin(), path.end(), numbers[i]) != path.end()) { | |
// Adding same number twice would make the permutation | |
// invalid, so skip this number from consideration. | |
continue; | |
} | |
path.push_back(numbers[i]); // consider this possibility. | |
recurse(path); // recursively solve. | |
path.pop_back(); // undo the considered possibility. | |
} | |
} | |
public: | |
vector<vector<int>> permute(vector<int>& nums) { | |
numbers = nums; | |
vector<int> path; // to keep track of considered numbers | |
// and their order. Initially empty. | |
recurse(path); | |
return answer; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment