题解 | #全排列#

全排列

http://www.nowcoder.com/practice/5632c23d0d654aecbc9315d1720421c1

非递归方式

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
#include <functional>
#include <vector>

using namespace std;

//递归和循环都写一个 



string getnext(string s){
	//当最后两位是升序的时候,就调成降序;是降序的时候,就往前while寻求进位。
	int n = s.size();
	if(n==1){
		return "-1";
	}
	if(s[n-2] < s[n-1]){
		sort(s.end()-2,s.end(),greater<char>());
		return s;
	}else if(n==2){
		return "-1";
	}else{
		int i = n-3;
		while(i>=0){
			if(s[i] < s[i+1]){//则可以实现“进位”
				int j = n-1;
				while(s[j] <= s[i]){
					j--;
				} 
				swap(s[i],s[j]);
				sort(s.begin()+i+1,s.end());
				return s;
			}
			i--;
		}
		return "-1";
	}
}

void xunhuan(string s){
	do{
		printf("%s\n",s.c_str());
		s = getnext(s);
	}while(s != "-1");
	return;
}

int main(){
	string s;
	while(cin >> s){
		sort(s.begin(),s.end());
//		digui(s, 0);
		xunhuan(s);
		s.clear();
	}
	return 0;
}
全部评论

相关推荐

牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
每晚夜里独自颤抖:你cet6就cet6,cet4就cet4,你写个cet证书等是什么意思。专业技能快赶上项目行数,你做的这2个项目哪里能提现你有这么多技能呢
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-30 18:19
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务