全排列 next_permutation() 函数的用法
在头文件<algorithm>里面有如下代码:
int a[];
do
{
}
while(next_permutation(a,a+n));
可产生1~n的全排列有如下代码:
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int n;
while(scanf("%d",&n)&&n){
int a[1000];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
sort(a,a+n);
do{
for(int i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}while(next_permutation(a,a+n));
}
return 0;
}
例如输入
3
1 0 2
如果有sort()
输出为
0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
若无sort()
则输出为
1 0 2
1 2 0
2 0 1
2 1 0
可以发现函数next_permutation()是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。