LeetCode Next Permutation 生成下一个序列

Next Permutation

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be in-place, do not allocate extra memory.

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

本题关键也是理解题意是什么,然后画图,总结规律。

1 从尾端往前寻找前一个元素比后一个元素小的位置i。找到这个位置之后,继续从后往前找,找到第一个大于num[i]的元素,交换;

2 i元素之后的元素排序,或者转置,都可以随你喜欢。 如果整个序列是倒序的,那么直接转置,或者排序都可以。

不过还有更加简单的LeetCode有史以来最简单的一句话程序,看下面。

2013-12-21 Update:

更新一个程序,我还是喜欢下面这个新写的程序,感觉思路更加清晰:

class Solution {
public:
	void nextPermutation(vector<int> &num)
	{
		int n = num.size();

		int i = n-2;
		while (i>=0 && num[i] >= num[i+1]) i--;

		if (i < 0)
		{
			reverse(num.begin(), num.end());
			return;
		}

		int k = n-1;
		while (num[k] <= num[i]) k--;

		swap(num[i], num[k]);

		reverse(num.begin()+i+1, num.end());
	}
};


程序如下:

void nextPermutation2(vector<int> &num)
	{
		if (num.size() < 2) return;

		for (int i=num.size()-1;;i--)
		{
			if (i == 0)
			{
				reverse(num.begin(), num.end());
				return;
			}

			if (num[i-1] < num[i])
			{
				int k = num.size()-1;
				//注意是<=不是<,否则出现如1,5,1这样会结果错误的。
				while (num[k] <= num[i-1])
				{
					k--;
				}
				swap(num[i-1], num[k]);
				reverse(num.begin()+i, num.end());
				return;
			}
		}
	}

	void nextPermutation3(vector<int> &num)
	{
		if(num.size()<2) return;

		for (int i=num.size()-1;;i--)
		{
			if (i == 0)
			{
				reverse(num.begin(), num.end());
				return;
			}

			if (num[i-1] < num[i])
			{
				int k = num.size()-1;
				//注意是<=不是<,否则出现如1,5,1这样会结果错误的。
				while (num[k] <= num[i-1])
				{
					k--;
				}
				swap(num[i-1], num[k]);
				sort(num.begin()+i, num.end());
				return;
			}
		}
	}


LeetCode有史以来最简单的一句话程序,调用STL函数库AC的程序:

void nextPermutation(vector<int> &num) 
	{
		next_permutation(num.begin(), num.end());
	}


//2014-1-26 update
class Solution126 {
public:
	void nextPermutation(vector<int> &num) 
	{
		int idx1 = num.size()-2, idx2 = num.size()-1;

		//num[idx1]>=num[idx1+1]一定要写>=,不能是>,举例没举好也会出错。
		for ( ; idx1>=0 && num[idx1] >= num[idx1+1]; idx1--);
		if (idx1 < 0)
		{
			reverse(num.begin(), num.end());
			return;
		}

		for ( ; idx2>=0 && num[idx2] <= num[idx1]; idx2--);

		swap(num[idx1], num[idx2]);
		reverse(num.begin()+idx1+1, num.end());
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值