-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutations.cpp
More file actions
39 lines (34 loc) · 945 Bytes
/
Permutations.cpp
File metadata and controls
39 lines (34 loc) · 945 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
33
34
35
36
37
38
39
/*
* Given a collection of numbers, return all possible permutations.
*
* For example,
* [1,2,3] have the following permutations:
* [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
*
*/
class Solution {
void do_permute(vector<int> &num, vector<vector<int> > &ret, vector<int> &line, int n) {
if (n == 0) {
ret.push_back(line);
return;
}
for (int i = 0; i < n; i++) {
line.push_back(num[i]);
swap(num[i], num[n-1]);
do_permute(num, ret, line, n - 1);
swap(num[i], num[n-1]);
line.pop_back();
}
}
public:
vector<vector<int> > permute(vector<int> &num) {
vector<vector<int> > ret;
int size = num.size();
if (size == 0) {
return ret;
}
vector<int> line;
do_permute(num, ret, line, size);
return ret;
}
};