计算全排列

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
#include<bits/stdc++.h>
using namespace std;
bool next_permutation(int a[], int s, int e)
{
if (s == e)
return false;
int i = e;
int j = i;
i--;
while (true)
{
if (j == s)
return false;
if (a[i] >= a[j])
{
j = i;
i--;
}
else
{
int k = e;
while (a[k] < a[i])k--;
swap(a[i], a[k]);
reverse(a+i+1, a+e+1);
return true;
}
}
}
int main()
{
int a[] = {1, 2, 3, 4};
do {
for (int i = 0;i < 4;i++)
cout << a[i] << " ";
printf("\n");
}while(next_permutation(a, 0, 3));
return 0;
}