C STL全排列的簡單實現

2021-07-30 06:06:26 字數 1349 閱讀 3982

next_permutation函式

組合數學中經常用到排列,這裡介紹乙個計算序列全排列的函式:

next_permutation(start,end),和prev_permutation(start,end)。這兩個函式作用是一樣的,區別就在於前者求的是當前排列的下乙個排列,後乙個求的是當前排列的上乙個排列。至於這裡的「前乙個」和「後乙個」,我們可以把它理解為序列的字典序的前後,嚴格來講,就是對於當前序列pn,他的下乙個序列pn+1滿足:不存在另外的序列pm,使pn

對於next_permutation函式,

其函式原型為:

#include

bool next_permutation(iterator start,iterator end)

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

我們來看下面這個例子:

[cpp]view plain

copy

print?

#include 

#include 

using

namespace std;  

int main()  

;  do

while(next_permutation(num,num+3));  

return 0;  

}  

#include #include using namespace std;

int main()

; do

{cout<

輸出結果為:

當我們把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進行排序。

C STL實現全排列

next permutation函式 組合數學中經常用到排列,這裡介紹乙個計算序列全排列的函式 next permutation start,end 和prev permutation start,end 這兩個函式作用是一樣的,區別就在於前者求的是當前排列的下乙個排列,後乙個求的是當前排列的上乙個...

全排列的實現

在c 的模板中,有一對專門用於實現數字或字元全排列的模板 next permutation biter,biter 和prev permutation biter,biter 前者實現向後排列,後者實現向前排列,即前者在原順序上依次產生較大的排列,後者則相反。舉個例子 假設需要產生以 354 為基礎...

全排列的實現

程式設計思路如下 擷取自 erlang程式設計 3.8 除錯的 include include include using namespace std void insert string str,char ch,vector aa void fun string array,vector a st...