数字全排列的下一个

Problem C 下一个

Time Limit: 1000ms    Memony Limit: 32768KB

Description

N个数的全排列是按字典序排列的,现在给你其中的一个排列,请你写出它的下一个。如123456的下一个是123465

312的下一个是3214321的下一个无。

Input

有多组测试数据,每组一行,每行有1n的排列,n<10

Ouput

下一个排列。

Sample Input

123456

312

4321

156324987

 

Sample Output

123465

321

156327489

要点:从后向前找到i,再在i后面找到一第一个比i大的j swap(i,j);然后把i+1到最后的所有数字sort排序如果找不到就说明该数字是逆序数,没有下一个排列。

实验代码:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int nextPermutation(int a[],int n) {
	for (int i = n - 1; i >= 0; i--)
	{
		for (int j = n - 1; j>i; j--)
		{
			if (a[i]<a[j])
			{
				swap(a[i], a[j]);
				sort(a + i + 1, a+n);
				return 1;
			}
		}
	}
	return -1;
}
int main()
{
	string s;
	int a[10];
	int len = 0;
	while (cin >> s) {
		len = s.length();
		for (int i = 0; i < len; i++) {
			a[i] = s[i] - '0';
		}
		if (nextPermutation(a, len) == -1) {
			cout << "无";
		}else {
			for (int i = 0; i < len; i++) {
				cout << a[i];
			}
		}
		cout << endl;
	}
	return 0

猜你喜欢

转载自blog.csdn.net/yky__xukai/article/details/80313381