next_permutation全排列

29 篇文章 0 订阅
25 篇文章 0 订阅

参考博客: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博客

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值