-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations.cpp
86 lines (79 loc) · 2.01 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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* =====================================================================================
*
* Filename: permutations.cpp
*
* Description: Permutations: Given a collection of distinct integers, return all
* possible permutations.
*
* Version: 1.0
* Created: 09/03/18 11:05:59
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <vector>
class Solution
{
public:
std::vector<std::vector<int>> permute(const std::vector<int>& nums)
{
std::vector<std::vector<int>> perms;
if (nums.size() == 0)
{
return perms;
}
std::vector<bool> visited(nums.size(), false);
std::vector<int> current;
dfs(nums, &visited, ¤t, &perms);
return perms;
}
private:
void dfs(const std::vector<int>& nums, std::vector<bool>* visited, std::vector<int>* current, std::vector<std::vector<int>>* perms)
{
if (current->size() == nums.size())
{
perms->push_back(*current);
return;
}
for (size_t i = 0; i < nums.size(); i++)
{
if (!visited->at(i))
{
visited->at(i) = true;
current->push_back(nums[i]);
dfs(nums, visited, current, perms);
current->pop_back();
visited->at(i) = false;
}
}
}
};
int main(int argc, char* argv[])
{
std::vector<int> nums = {1, 2, 3, 4};
if (argc > 3)
{
nums.clear();
for (int i = 1; i < argc; i++)
{
nums.push_back(atoi(argv[i]));
}
}
auto perms = Solution().permute(nums);
for (auto& p: perms)
{
for (auto n: p)
{
printf("%d ", n);
}
printf("\n");
}
return 0;
}