`
jgsj
  • 浏览: 957092 次
文章分类
社区版块
存档分类
最新评论

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());
	}
};

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics