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];
			}
		}
	}
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值