-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.cpp
More file actions
32 lines (29 loc) · 941 Bytes
/
permutations.cpp
File metadata and controls
32 lines (29 loc) · 941 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <vector>
#include <unordered_set>
class Solution {
private:
std::vector<std::vector<int>> solution;
public:
std::vector<std::vector<int>> permute(std::vector<int>& nums) {
std::unordered_set<int> usedNums; // Keep track of which numbers have been used in each recursive iteration
std::vector<int> perm;
helper(nums, usedNums, perm);
return solution;
}
void helper(std::vector<int>& nums, std::unordered_set<int> used,std::vector<int> perm) {
if (perm.size() == nums.size()) {
solution.push_back(perm);
return;
}
// backtrack
for (int i=0; i<nums.size(); i++) {
if (used.find(i)== used.end()) {
perm.push_back(nums[i]);
used.insert(i);
helper(nums, used, perm);
perm.pop_back();
used.erase(i);
}
}
}
};