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

C++中全排列函式next_permutation 用法

全排列參考了兩位的部落格 感謝!

http://blog.sina.com.cn/s/blog_9f7ea4390101101u.html

http://blog.csdn.net/ac_gibson/article/details/45308645

早就聽說了了next_permutation 產生全排列的強大,一直到昨晚遇到一個對字串產生全排列的問題才知道這個函式的強大,我們隊是按照dfs去搞全排列,然後在進行字串的匹配,結果寫的很長,過程中還各種debug。。。於是決定今天學一下…

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進行排序。

也可以對字元…

next_permutation 自定義比較函式 POJ 1256

題目中要求的字典序是

//'A'<'a'<'B'<'b'<...<'Z'<'z'.
。。。

#include<iostream> //poj 1256 Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b) 
{
 if(tolower(a)!=tolower(b))//tolower 是將大寫字母轉化為小寫字母.
 return tolower(a)<tolower(b);
 else
 return a<b;
}
int main()
{
 char ch[20];
 int n;
cin>>n;
 while(n--)
{
scanf("%s",ch);
sort(ch,ch+strlen(ch),cmp);
 do
{
printf("%s\n",ch);
}while(next_permutation(ch,ch+strlen(ch),cmp));
}
 return 0;
}