next_permutation函數 (產生全排列)

來源:互聯網
上載者:User

標籤:

這是一個求一個排序的下一個排列的函數,可以遍曆全排列,要包含標頭檔<algorithm>
下面是以前的筆記    與之完全相反的函數還有prev_permutation
 
 
(1) int 類型的next_permutation
 
int main()
{
 int a[3];
a[0]=1;a[1]=2;a[2]=3;
 do
{
cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
} while (next_permutation(a,a+3)); //參數3指的是要進行排列的長度
 
//如果存在a之後的排列,就返回true。如果a是最後一個排列沒有後繼,返回false,每執行一次,a就變成它的後繼
 
 
}
 
輸出:
 
 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
 
 
 
若排列本來就是最大的了沒有後繼,則next_permutation執行後,會對排列進行字典升序排序,相當於迴圈
 
 int list[3]={3,2,1};
next_permutation(list,list+3);
cout<<list[0]<<" "<<list[1]<<" "<<list[2]<<endl;
 
//輸出: 1 2 3

 
 
 
 
(2) char 類型的next_permutation
 
int main()
{
 char ch[205];
cin >> ch;
 
sort(ch, ch + strlen(ch) );
//該語句對輸入的數組進行字典升序排序。如輸入9874563102 cout<<ch; 將輸出0123456789,這樣就能輸出全排列了
 
 char *first = ch;
 char *last = ch + strlen(ch);
 
 do {
cout<< ch << endl;
}while(next_permutation(first, last));
 return 0;
}
 
//這樣就不必事Crowdsourced Security Testing道ch的大小了,是把整個ch字串全都進行排序
//若採用 while(next_permutation(ch,ch+5)); 如果只輸入1562,就會產生錯誤,因為ch中第五個元素指向未知
//若要整個字串進行排序,參數5指的是數組的長度,不含結束符

 
 
 
 
 
(3) string 類型的next_permutation
 
int main()
{
 string line;
 while(cin>>line&&line!="#")
{
 if(next_permutation(line.begin(),line.end())) //從當前輸入位置開始
cout<<line<<endl;
 else cout<<"Nosuccesor\n";
}
}
 
 
 
int main()
{
 string line;
 while(cin>>line&&line!="#")
{
sort(line.begin(),line.end());//全排列
cout<<line<<endl;
 while(next_permutation(line.begin(),line.end()))
cout<<line<<endl;
}
}
 
 
 
 
 
 
 next_permutation 自訂比較函數
 
 
#include<iostream> //poj 1256 Anagram
#include<string>
#include<algorithm>
using namespace std;
int cmp(char a,char b) //‘A‘<‘a‘<‘B‘<‘b‘<...<‘Z‘<‘z‘.
{
 if(tolower(a)!=tolower(b))
 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;
}

next_permutation函數 (產生全排列)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.