-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.cpp
More file actions
28 lines (25 loc) · 826 Bytes
/
permutations.cpp
File metadata and controls
28 lines (25 loc) · 826 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
class Solution {
public:
void backtrack(vector<vector<int>>& ans, vector<int>& nums, vector<int>& output, vector<bool> visit, int depth, int end) {
if (depth == end) {
ans.push_back(output);
return;
}
for (int idx = 0; idx < end; idx++) {
if (!visit[idx]) {
output.push_back(nums[idx]);
visit[idx] = true;
backtrack(ans, nums, output, visit, depth + 1, end);
visit[idx] = false;
output.pop_back();
}
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> output;
vector<bool> visit(nums.size(), false);
backtrack(ans, nums, output, visit, 0, nums.size());
return ans;
}
};