prev_permutation函数和next_permutation函数
全排列在c++中有标准库,直接调用就行。
头文件:#include
函数模板:next_permutation(arr, arr+size);
函数模板:prev_permutation(arr, arr+size);
std::next_permutation与std::prev_permutation可以获取数字或者是字符的全排列std::next_permutation提供升序、
std::prev_permutation提供降序。
例如:3 2 1,只有上一个较小值,没有下一个较大值。
1 2 3只有下一个较大值,没有上一个较小值。
2 1 3 的上一个较小值为 1 3 2,下一个较大值为 2 3 1.
解释:arr为数组,size为数组长度。
next_permutation(arr, arr+size);当有下一个较大值返回1,否则返回0,
prev_permutation(arr, arr+size);当有上一个较小值返回1,否则返回0。
next_permutation(node,node+n,cmp)可以对结构体num按照自定义的排序方式cmp进行排序。
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
int arr2[] = {3,2,1};
cout<<"用prev_permutation对3 2 1的全排列"<<endl;
do
{
cout << arr2[0] << ' ' << arr2[1] << ' ' << arr2[2]<<'\n';
}
while ( prev_permutation(arr2,arr2+3) ); //每运行一次函数,会交换顺序
int arr1[] = {1,2,3};
cout<<"用next_permutation对1 2 3的全排列"<<endl;
do
{
cout << arr1[0] << ' ' << arr1[1] << ' ' << arr1[2] <<'\n';
}
while ( next_permutation(arr1,arr1+3) ); //每运行一次函数,会交换顺序
return 0;
}
在这里插入图片描述
这两个函数会自动去重;
在排列之前如果是无序的一定要进行排序后在使用否则会丢失情况,只能找出该序列之后的全排列数;
如果改成 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
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;
}
//这样就不必事先知道ch的大小了,是把整个ch字符串全都进行排序
//若采用 while(next_permutation(ch,ch+5)); 如果只输入1562,就会产生错误,因为ch中第五个元素指向未知
//若要整个字符串进行排序,参数5指的是数组的长度,不含结束符
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;
}