Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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