版权声明:victor https://blog.csdn.net/qq_40155097/article/details/83413338
看见很多人用DFS
但我今天想说的是,STL教你做人
昨天我和dalao比谁的速度快
结果一个是
,一个是
STL完胜
首先我要用一个神奇的函数
组合数学中经常用到排列,这里介绍一个计算序列全排列的函数:
,和
。这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后,严格来讲,就是对于当前序列
,他的下一个序列
满足:不存在另外的序列
,使
.
对于 函数,其函数原型为:
#include <algorithm>
bool next_permutation(iterator start,iterator end)
当当前序列不存在下一个排列时,函数返回false,否则返回true
我们来看下面这个例子:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int num[3]={1,2,3};
do
{
cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;
}while(next_permutation(num,num+3));
return 0;
}
输出结果为:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
当我们把
中的3改为2时,输出就变为了:
1 2 3
2 1 3
由此可以看出,
函数是对数组num中的前n个元素进行全排列,同时并改变
数组的值。
另外,需要强调的是,
在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。比如,如果数组num初始化为2,3,1,那么输出就变为了:
2 3 1
3 1 2
3 2 1
此外,
可以对结构体
按照自定义的排序方式
进行排序。
现在我们就可以开始了
先贴代码:
#include<algorithm>
#include<cstdio>
using namespace std;
int main()
{
//freopen("fuck.in", "r", stdin);
//freopen("fuck.out", "w", stdout);
int n;
scanf("%d",&n);
int a[n + 5];
for(int i = 0; i <= n - 1;i++)
a[i] = i + 1;
do
{
for(int i = 0;i <= n - 1;i++)
printf("%5d",a[i]);
printf("\n");
}while(next_permutation(a,a + n)); //函数的运用
return 0;
//fclose(stdin);
//fclose(stdout);
}