-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperm.cpp
More file actions
91 lines (86 loc) · 1.9 KB
/
Copy pathperm.cpp
File metadata and controls
91 lines (86 loc) · 1.9 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
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
87
88
89
90
91
//
// Heap's algorithm
// Heap's algorithm generates all possible permutations of n objects.
// It was first proposed by B. R. Heap in 1963.[1]
// The algorithm minimizes movement:
// it generates each permutation from the previous one by interchanging
// a single pair of elements; the other n−2 elements are not disturbed.
// In a 1977 review of permutation-generating algorithms, Robert Sedgewick
// concluded that it was at that time the most effective algorithm for
// generating permutations by computer.[2]
// reference:
// https://en.wikipedia.org/wiki/Heap%27s_algorithm
#include <iostream>
#include <vector>
#include <utility>
using namespace std;
void perm_fast(std::vector<int>& l, const int n)
{
if(n == 1)
{
for(auto i: l)std::cout << i <<" ";
std::cout << std::endl;
}
else
{
for(int i = 0; i < n - 1; ++i)
{
perm_fast(l, n - 1);
if(n % 2 == 0)
std::swap(l[i], l[n-1]);
else
std::swap(l[n-1], l[0]);
}
perm_fast(l, n - 1);
}
}
void perm_backtrack(std::vector<int>& l, const int n)
{
if(n == 1)
{
for(auto i: l)std::cout << i <<" ";
std::cout << std::endl;
}
for(int i = 0; i < n; ++i)
{
std::swap(l[i], l[n-1]);
perm_backtrack(l, n -1);
std::swap(l[i], l[n-1]);
}
}
void dfs(std::vector<int>& a, std::vector<bool>& book, int step, const int n)
{
if(step == n)
{
for(int i: a)
std::cout << i << " ";
std::cout << std::endl;
}
else
{
for(int i = 0; i < n ; ++i)
{
if(!book[i])
{
a[step] = i+1;
book[i] = true;
dfs(a, book, step + 1, n);
book[i] = false;
}
}
}
}
int main(int argc, char const *argv[])
{
const int n = 3;
std::vector<int> a(n, 0);
for(int i = 0; i < n; ++i) a[i] = i+1;
perm_backtrack(a, n);
std::cout <<"------------------------\n";
for(int i = 0; i < n; ++i) a[i] = i+1;
perm_fast(a, n);
std::cout <<"------------------------\n";
std::vector<bool> book(n, false);
dfs(a, book, 0, n);
return 0;
}