全排列 next_permutation() 函數的用法

在頭文件<algorithm>裏面有以下代碼:html

 

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("\n"); 16         }while(next_permutation(a,a+n)); 17  } 18     return 0; 19 }

 

 

例如輸入函數

3spa

1 0 2code

若是有sort()orm

輸出爲htm

0 1 2
0 2 1
1 0 2
1 2 0
2 0 1
2 1 0
blog

若無ci

則輸出爲博客

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

相關文章
相關標籤/搜索