Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created June 4, 2020 01:12
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/1b6a2a13ab12ab317cb609c2eef77423 to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/1b6a2a13ab12ab317cb609c2eef77423 to your computer and use it in GitHub Desktop.
Leetcode #46: Permutations
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