next_permutation函數

next_permutation()這是一個求全排列的函數,返回值爲bool型,若是後面還有排列返回true,不然返回false。ios

int 類型數組

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是要求全排列的長度,和sort同樣。
函數

當a數組爲3 2 1是返回falsespa

 

char類型排序

int main()
{
 char ch[205];
cin >> ch;
sort(ch, ch + strlen(ch) );
 char *first = ch;
 char *last = ch + strlen(ch);
 do {
cout<< ch << endl;
}while(next_permutation(first, last));
 return 0;
}
 
把整個ch字符串全都進行排序,按字典升序ci

 

string 類型字符串

 

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;
}
}string

 

 

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;
}it

相關文章
相關標籤/搜索