c++ 全排列的实现

一.使用next_permutation进行全排列

next_permutation到底是做什么的呢?next_permutation是用于求下一个排列,默认是升序排列

使用next_permutation需要头文件#include<algorithm>

函数原型:
bool next_permutation(iterator start,iterator end);

bool next_permutation(iterator start,iterator end,compare cmp);

那么next_permutation是怎么求下一个排列的呢?其实,next_permutation在求下一个排列的时候,会返回是否有比它排名更靠后的排列,我们可以根据 next_permutation 的返回值求出全排列

例如 "4 3 2 1"就没有下一个排列,它是排名最靠后的.

 所以,next_permutation实际上求的是比它更靠后的字典序列。

#include<iostream>
#include<algorithm>
using namespace std;
//bool next_permutation(char *start,char *end){
//	char *cur=end-1,*pre=cur-1;
//	while(cur>start&&*pre>=*cur)cur--,pre--;
//	if(cur<=start)return false;
//	for(cur=end-1;*cur<=*pre;cur--)
//	swap(cur,pre);
//	reverse(pre+1,end);
//	return true;
//}
int main(){
	int num[4]={1,2,3,4};
	do{
		cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<" "<<num[3]<<endl;
	}while(next_permutation(num,num+4));
	return 0;
}

当然,也可以自己实现next_permutation

与sort()排序函数相似,可以添加第三个参数cmp实现对数组进行降序排序

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(int a,int b){
	return a>b;
}
int main(){
	int num[3]={3,2,1};
	do{
		cout<<num[0]<<" "<<num[1]<<" "<<num[2]<<" "<<endl;
	}while(next_permutation(num,num+3,cmp));
	return 0;
}

 对string类型排序

#include<iostream>
#include<algorithm>
#include<string>
using namespace std;
int main(){
	string s;
	cin>>s;
	do{
		cout<<s<<endl;
	}while(next_permutation(s.begin(),s.end()));
	return 0;
}

当我输入abc时,运行结果如下:

二. 使用dfs实现全排列

#include<iostream>
#include<algorithm>
using namespace std;
int a[3]={2,1,3};
int path[3];
bool st[3];//存储这个数是否用过 
void dfs(int u){
	if(u==3){//递归结束 
		for(int i=0;i<3;i++)printf("%d",path[i]);
		puts("");
		return ;
	}
	for(int i=0;i<3;i++){
		if(!st[a[i]]){
			path[u]=a[i];
			st[a[i]]=true;
			dfs(u+1);
			st[a[i]]=false;//回到之前状态 
		}
	}
}
int main(){
	dfs(0);
	return 0;
}

运行结果:

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无限酸奶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值