forked from cpselvis/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution046.cpp
More file actions
53 lines (49 loc) · 963 Bytes
/
solution046.cpp
File metadata and controls
53 lines (49 loc) · 963 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
* Permutations
* Backtack algorithm.
*
* cpselvis([email protected])
* August 31th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<vector<int> > permute(vector<int>& nums) {
vector<vector<int> > ret;
backtack(ret, nums, 0);
return ret;
}
void backtack(vector<vector<int> > &ret, vector<int> &nums, int index)
{
if (index == nums.size())
{
ret.push_back(nums);
}
else
{
for (int i = index; i < nums.size(); i ++)
{
swap(nums[index], nums[i]);
backtack(ret, nums, index + 1);
swap(nums[index], nums[i]);
}
}
}
};
int main(int argc, char **argv)
{
int arr[3] = {1, 2, 3};
vector<int> vec(arr + 0, arr + 3);
Solution s;
vector<vector<int> > ret = s.permute(vec);
for (int i = 0; i < ret.size(); i ++)
{
for (int j = 0; j < ret[i].size(); j ++)
{
cout << ret[i][j] << " ";
}
cout << endl;
}
}