王道机试指南---第八章---递归与分治---8.2全排列

8.2全排列

1.递归方式

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>

using namespace std;

const int MAXN=10;

bool visit[MAXN];		//记录递归过程中某个元素是否被使用过 
char sequence[MAXN];	//记录每个排列什么方式 

void GetPermutation(string str,int index){		//index为深度 
	if(index==str.size()){
		for(int i=0;i<str.size();++i){
			printf("%c",sequence[i]);
		}
		printf("\n");
	}
	
	for(int i=0;i<str.size();++i){
		if(visit[i]){
			continue;
		}
		visit[i]=true;
		sequence[index]=str[i];
		GetPermutation(str,index+1);
		visit[i]=false;
	}
}

int main(){
	string str;
	while(cin>>str){
		sort(str.begin(),str.end());
		GetPermutation(str,0);
		printf("\n");
	}
	return 0;
}

没能深入理解递归过程----dev 调试未成功

2.非递归方式
从上一个排列得到下一个排列

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>

using namespace std;

bool GetNextPermutation(string &str){		//bool类型,因为不一定有下一个全排列
	int n=str.size();
	int index=n-2;
	while(index>=0&&str[index]>=str[index+1]){//找到不是降序的下标 
		index--;
	} 
	if(index<0){		//说明全部数都是降序了
		return false; 
	}
	for(int i=n-1;i>index;--i){		//从后往前找,找到第一个大于index下标的数,交换
		if(str[i]>str[index]){
			swap(str[index],str[i]);	//依旧是个降序的 
			break;
		} 
		
	}
	reverse(str.begin()+index+1,str.end());//将升序的局部逆序 
	return true;
}


int main(){
	string str;
	while(cin>>str){
		sort(str.begin(),str.end()); //全部升序,再逐一降序
		do{
			cout<<str<<endl;
		}while(GetNextPermutation(str));
		cout<<endl;
	}
	return 0;
}

3.系统函数next_permutation

#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>

using namespace std;

int main(){
	string str;
	while(cin>>str){
		sort(str.begin(),str.end());
		do{
			cout<<str<<endl;
		}while(next_permutation(str.begin(),str.end()));
		cout<<endl;
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Miraitowa_FTY

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

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

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

打赏作者

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

抵扣说明:

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

余额充值