-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path46.Permutations.h
More file actions
51 lines (42 loc) · 1.13 KB
/
46.Permutations.h
File metadata and controls
51 lines (42 loc) · 1.13 KB
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
49
50
51
/*
bluepp
2014-06-19
2014-07-19
2014-11-05
2014-11-09
2014-11-29
May the force be with me!
Problem: Permutations
Source: https://oj.leetcode.com/problems/permutations/
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...
*/
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int> >res;
vector<bool> avail(nums.size(), true);
_perm(nums, avail, {}, res);
return res;
}
void _perm(vector<int> &num, vector<bool> &avail, vector<int> vec, vector<vector<int> >&res)
{
if(vec.size() == num.size())
{
res.push_back(vec);
return;
}
for (int i = 0; i < num.size(); i++)
{
if (avail[i])
{
avail[i] = false;
vec.push_back(num[i]);
_perm(num, avail, vec, res);
vec.pop_back();
avail[i] = true;
}
}
}