LeetCode刷题(C++)——Next Permutation(Medium)

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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

思路:C++的STL中有一个next_permutation的函数,函数功能是生成当前排列的下一个排列,此处就是让我们自己实现这个next_permutation

其实实现这个函数功能不难,主要是我们需要先了解这个函数是如何得到下一个排列的,举个例子:对于[1,3,6,5,4,2]这个排列,它的下一个排列为[1,4,2,3,5,6],这个是怎么得到的呢???

(1)从都往前遍历,如果后一个数比前一个数大,继续往前寻找,直到找到第一个不是依次增长的数,记录该数位置为i;

(2)此时对应两种情况:

一是该序列为递增序列,即元素从后往前都是递增的,说明这个序列为最后一个排列,那么下一个序列为第一个排列,把所有元素翻转即可,如{4,3,2,1}->{1,2,3,4};

二是如果找到的存在且 i>0,那么此时从i+1开始往后遍历,寻找第一个比i位置上的数小的数,记录它的位置为j,此时交换第i和第j-1位置的数,然后将i位置以后的所有数进行翻转,就是我们要的下一个排列。

代码如下:

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if (nums.size() < 2)
			return;
		int i=nums.size()-1;
		while (i > 0 && nums[i] <= nums[i - 1])
			i--;
		i--;
		if (i >= 0) {
			int j = i + 1;
			while (j<nums.size() && nums[j]>nums[i])
				j++;
			j--;
			swap(nums[i], nums[j]);
		}
		reverse(nums, i + 1, nums.size() - 1);
	}

	void reverse(vector<int>& nums, int i, int j)
	{
		if (i > j)
			return;
		while (i < j)
			swap(nums[i++], nums[j--]);
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值