next_permutation()能夠按字典序生成所給區間的全排列。html
在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}沒有下一個元素。c++
next_permutation()和prev_permutation()包含在頭文件#include <algorithm>中。函數
注意:雖然最後一個排列沒有下一個排列,用next_permutation()會返回false,可是使用了這個方法後,序列會變成字典序列的第一個,如cba變成abc。prev_permutation同理。spa
用法:3d
這裏咱們舉例0,1,2,3,4的全排列。code
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 int main(){ 5 int a[5]={0,1,2,3,4}; 6 int ans=0; 7 while(ans<20){ 8 next_permutation(a,a+5); 9 for(int i=0;i<5;i++){ 10 cout<<a[i]; 11 } 12 cout<<endl; 13 ans++; 14 } 15 return 0; 16 }
輸出結果:htm
對於prev_permutation():blog
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 int main(){ 5 int a[5]={0,1,2,3,4}; 6 int ans=0; 7 while(ans<20){ 8 prev_permutation(a,a+5); 9 for(int i=0;i<5;i++){ 10 cout<<a[i]; 11 } 12 cout<<endl; 13 ans++; 14 } 15 return 0; 16 }
輸出結果:get