詳談全排列next_permutation() 函數(shù)的用法(推薦)
這是一個c++函數(shù),包含在頭文件<algorithm>里面,下面是基本格式。
1 int a[]; 2 do{ 3 4 }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
若無
則輸出為
1 0 2
1 2 0
2 0 1
2 1 0
可以發(fā)現(xiàn)少了許多種組合方法。
不過,仔細比較各種組合方法和有無sort()的輸出,可以發(fā)現(xiàn)函數(shù)next_permutation()是按照字典序產生排列的,并且是從數(shù)組中當前的字典序開始依次增大直至到最大字典序。
以上這篇詳談全排列next_permutation() 函數(shù)的用法(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C語言中getopt()函數(shù)和select()函數(shù)的使用方法
這篇文章主要介紹了C語言中getopt()函數(shù)和select()函數(shù)的使用方法,是C語言入門學習中的基礎知識,需要的朋友可以參考下2015-09-09