题解 | #全排列#

全排列

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;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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