next_permutation
这个函数每运行一次就可以把数组排成下一个字典序数列;与之对应的是prev_permutation,即排出上一个字典序
很容易得出总排列数为: \(A_{n}^{n}=n!\)
#include<iostream>
#include<algorithm>
using namespace std;
int a[10];
int sum = 1;
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
a[i] = i;
sum *= i;
printf("%5d", i);
}
cout << endl;
for (int i = 1; i < sum; i++)
{
next_permutation(a + 1, a + n + 1);
for (int j = 1; j <= n; j++) printf("%5d", a[j]);
cout << endl;
}
return 0;
}