Leetcode 31. 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 and use only constant 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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

解题思路

这个问题实际上是一个全排序问题。比如需要交换vector中第i个元素和第j个元素(vector[i] < vector[j]),交换过后vector[i]之后的元素在进行一次排序。因此本题的关键是找到要交换的元素。这里可以倒序查找,即从序列尾部向头部查找,寻找到一个使得这个局部序列不成递减序列的数:

假设序列为[6, 5, 4, 8, 7, 5, 1],即从尾部的1开始逐个向前查找,可以发现8 7 5 1成递减序列,而在前面一个的4与这四个数不构成递减序列,则4就是我们要交换位置的元素之一;然后再从后面的递减序列从尾向头寻找到第一个比4大的元素,交换它们,在对原递减序列位置的元素进行排序即可。

代码如下:

class Solution {
public:
	void nextPermutation(vector<int>& nums) {
		int leng = nums.size();
		vector<int> vec = nums;  //临时存储nums

		int p = leng - 1;
		while (p > 0) {
			if (vec[p] > vec[p - 1]) {  //判断是否为递减数列
				break;
			}
			else {
				p--;
			}
		}
		if (p == 0) {  //如果是递减序列
			for (int i = 0; i < leng; i++) {
				nums[i] = vec[leng - 1 - i];
			}
		}
		else {
			int cast = p - 1;  // nums[p] > nums[p-1]
			for (int i = leng - 1; i >= p; i--) {  //按照从vec[leng-1]到vec[p]的顺序,找到第一个比vec[p-1]大的数,将这两个数交换位置
				if (vec[cast] < vec[i]) {
					int temp = vec[cast];
					vec[cast] = vec[i];
					vec[i] = temp;
					break;
				}
			}
			sort(vec.begin() + p, vec.end());
			for (int i = 0; i < leng; i++) {
				nums[i] = vec[i];
			}
		}
	}
};

猜你喜欢

转载自blog.csdn.net/sysu_chan/article/details/80093741