next_permutation函数

next_permutation()这是一个求全排列的函数,返回值为bool型,如果后面还有排列返回true,否则返回false。

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是返回false

 

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字符串全都进行排序,按字典升序

 

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

 

 

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

posted @ 2015-08-18 11:10  ~Arno  阅读(283)  评论(0编辑  收藏  举报