forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Permutations.cpp
43 lines (42 loc) · 1.36 KB
/
Permutations.cpp
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
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
// no extra space
void permuteUtils(int idx, vector<int> &num, vector<vector<int> > &result) {
if(idx == num.size() - 1) {
result.push_back(num);
return;
}
for(int i = idx; i < num.size(); ++i) {
swap(num[idx], num[i]);
permuteUtils(idx + 1, num, result);
swap(num[idx], num[i]);
}
}
// with extra space
void permute(vector<int> &container, vector<bool> &visited, vector<int> &num, vector<vector<int> > &result) {
if(container.size() == num.size()) {
result.push_back(container);
return;
}
for(int i = 0; i < num.size(); ++i) {
if(!visited[i]) {
visited[i] = true;
container.push_back(num[i]);
permute(container, visited, num, result);
visited[i] = false;
container.pop_back();
}
}
}
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > result;
if(num.size() < 0) return result;
/*
vector<bool> visited(num.size() + 1, false);
vector<int> container;
permute(container, visited, num, result);
*/
permuteUtils(0, num, result);
return result;
}
};