组合数学中经常用到排列,这里介绍一个计算序列全排列的函数:next_permutation(start,end),和prev_permutation(start,end)。
头文件
< algorithm >
作用
这两个函数作用是一样的,区别就在于前者求的是当前排列的下一个排列,后一个求的是当前排列的上一个排列。
至于这里的“前一个”和“后一个”,我们可以把它理解为序列的字典序的前后,严格来讲,就是对于当前序列pn,他的下一个序列pn+1满足:不存在另外的序列pm,使pn<pm<pn+1;同理,上一个序列pn-1满足:不存在另外的序列pm,使pn-1<pm<pn;
实例
int main()
{
int a[4]={1,2,3};
char b[10]="123";
string c="123";
do{
cout<<a[0]<<a[1]<<a[2]<<endl;
} while(next_permutation(a,a+3));
do{
cout<<b[0]<<b[1]<<b[2]<<endl;
}while(next_permutation(b,b+3));
do{
cout<<c<<endl;
}while(next_permutation(c.begin(),c.end()));
return 0;
}
该例程很好的表现了三个情况——整形数组,字符数组跟string字符串的一个枚举情况。
同时,如果已经处于最后一个最大的字典序,用next_permutation则不会改变;同理,如果处于第一个最小的字典序状态,用prev_permutation则也不会改变。
再贴一个prev_permutation的例程,用法跟next_permutation一样。
int a[4]={3,2,1};
do{
cout<<a[0]<<a[1]<<a[2]<<endl;
} while(prev_permutation(a,a+3));