1. 程式人生 > >C++STL中全排列函式next_permutation的使用

C++STL中全排列函式next_permutation的使用

   next_permutation函式

    組合數學中經常用到排列,這裡介紹一個計算序列全排列的函式:next_permutation(start,end),和prev_permutation(start,end)。這兩個函式作用是一樣的,區別就在於前者求的是當前排列的下一個排列,後一個求的是當前排列的上一個排列。至於這裡的“前一個”和“後一個”,我們可以把它理解為序列的字典序的前後,嚴格來講,就是對於當前序列pn,他的下一個序列pn+1滿足:不存在另外的序列pm,使pn<pm<pn+1.

對於next_permutation函式,其函式原型為:

     #include <algorithm>

     bool next_permutation(iterator start,iterator end)

噹噹前序列不存在下一個排列時,函式返回false,否則返回true

我們來看下面這個例子:

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int num[3]={1,2,3};
    do
    {
        cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<endl;
    }while(next_permutation(num,num+3));
    return 0;
}


輸出結果為:


當我們把while(next_permutation(num,num+3))中的3改為2時,輸出就變為了:


由此可以看出,next_permutation(num,num+n)函式是對陣列num中的前n個元素進行全排列,同時並改變num陣列的值。

另外,需要強調的是,next_permutation()在使用前需要對欲排列陣列按升序排序,否則只能找出該序列之後的全排列數。比如,如果陣列num初始化為2,3,1,那麼輸出就變為了:


此外,next_permutation(node,node+n,cmp)可以對結構體num按照自定義的排序方式cmp進行排序。