全排列 next_permutation() 函数的用法

在头文件<algorithm>里面有如下代码:

int a[];
do
{

}
while(next_permutation(a,a+n));

可产生1~n的全排列有如下代码:

 1 #include <stdio.h>
 2 #include <algorithm>
 3 using namespace std;
 4 int main(){
 5     int n;
 6     while(scanf("%d",&n)&&n){
 7         int a[1000];
 8         for(int i=0;i<n;i++){
 9             scanf("%d",&a[i]);
10         }
11         sort(a,a+n);
12         do{
13             for(int i=0;i<n;i++)
14                 printf("%d ",a[i]);
15             printf("
");
16         }while(next_permutation(a,a+n));
17     }
18     return 0;
19 }

例如输入

3

1 0 2

如果有sort()

输出为

0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0

若无

则输出为

1 0 2
1 2 0
2 0 1
2 1 0

发现函数next_permutation()是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序,在ACM International Collegiate Programming Contest, Egyptian Collegiate Programming Contest (2015)  Arab Academy for Science and Technology - Alexandria, November 6th, 2015 A题就可以采用next_permutation()。

原博客:https://www.cnblogs.com/My-Sunshine/p/4985366.html

 
原文地址:https://www.cnblogs.com/weixq351/p/9497108.html