這是一個求一個排序的下一個排列的函數,可以遍歷全排列,要包含頭文件<algorithm>
與之完全相反的函數還有prev_permutation
在STL中,除了next_permutation外,還有一個函數prev_permutation,兩者都是用來計算排列組合的函數。
前者是求出下一個排列組合,而后者是求出上一個排列組合。所謂“下一個”和“上一個”,書中舉了一個簡單的例子:
對序列 {a, b, c},每一個元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一個序列即為{a, c, b},而{a, c, b}的上一個序列即為{a, b, c},同理可以推出所有的六個序列為:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}沒有上一個元素,{c, b, a}沒有下一個元素。
(1) int 類型的next_permutation
#include<iostream> #include<stdio.h> #include<queue> #include<string> #include<string.h> #include<algorithm> using namespace std; int main() { int a[3]={1,2,3}; do { cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl; }while(next_permutation(a,a+3)); return 0; }
輸出
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
如果改成 while(next_permutation(a,a+2));
則輸出:
1 2 3
2 1 3
只對前兩個元素進行字典排序
顯然,如果改成 while(next_permutation(a,a+1)); 則只輸出:1 2 3
(2)char 類型的next_permutation
#include<iostream> #include<stdio.h> #include<queue> #include<string> #include<string.h> #include<algorithm> using namespace std; int main() { char ch[205]; cin>>ch; sort(ch,ch+strlen(ch)); char *first =ch; char *last=ch+strlen(ch); do{ cout<<ch<<endl; }while(next_permutation(first,last)); return 0; }