forked from leetcoders/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPermutations.h
48 lines (44 loc) · 1.16 KB
/
Permutations.h
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
44
45
46
47
48
/*
Author: Annie Kim, [email protected]
Date: Apr 29, 2013
Update: Jul 19, 2013
Problem: Permutations
Difficulty: Easy
Source: http://leetcode.com/onlinejudge#question_46
Notes:
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].
Solution: dfs...
*/
class Solution {
public:
vector<vector<int>> res;
vector<vector<int>> permute(vector<int> &num) {
res.clear();
vector<bool> avail(num.size(), true);
vector<int> pum;
permuteRe(num, avail, pum);
return res;
}
void permuteRe(const vector<int> &num, vector<bool> &avail, vector<int> &pum)
{
if (pum.size() == num.size())
{
res.push_back(pum);
return;
}
for (int i = 0; i < num.size(); ++i)
{
if (avail[i])
{
avail[i] = false;
pum.push_back(num[i]);
permuteRe(num, avail, pum);
pum.pop_back();
avail[i] = true;
}
}
}
};