参考博客:C++中全排列函数next_permutation 用法_nextpermutation函数-CSDN博客
该函数在<algorithm>头文件中
(全排列的顺序是,在升序的情况下进行全排,在此基础上才有上下的排列的跳转。)
用法next_permutation(arry_start,arry_end);求当前排列的下一个排列
引申:prev_permutation(arry_start,arry_end);求当前排列的前一个排列。
注:next_permutation和prev_permutation的返回类型为bool类型,即true或false.
1.next_permutation最后一个排列变为了降序,即为全排列的最后一个,此降序序列的next_permutation为false,数组回到升序。
2.prev_permutation为next_permutation的逆过程,最后一个排列变为了升序,即为
全排列的第一个,此降序序列的prev_permutation为false,数组回到降序。
eg:123全排序有:123 132 213 231 312 321,当排序到321时,此时为降序,
再进行next_permutation,将回到123,但此时返回false.
对123进行perv_permutation,返回到最后一个排序321,返回true
3.其他情况返回true.
上代码:
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int a[5];
a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
//输出当前序列
cout<<"当前序列" ;
for(int i=0;i<=2;i++)
cout<<a[i];
cout<<endl;
//求下一个排列
while(next_permutation(a,a+3))
{
cout<<"下一次排列:";
for(int i=0;i<=2;i++)
cout<<a[i];
cout<<endl;
}
prev_permutation(a,a+3);
//输出当前序列
cout<<"当前序列" ;
for(int i=0;i<=2;i++)
cout<<a[i];
cout<<endl;
//求上一个排列
while(prev_permutation(a,a+3))
{
cout<<"上一次排列:";
for(int i=0;i<=2;i++)
cout<<a[i];
cout<<endl;
}
return 0;
}
结果演示:
此外,该函数还能自定义排序(按照自己想要的规则,进行大小限定,类似上一博客sort函数自定义排序)
形式:next_permutation(node,node+n,cmp)
具体例子参考博客:C++中全排列函数next_permutation 用法_nextpermutation函数-CSDN博客