Leetcode NO.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, 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

本题并不算难,但是却把我难住了。。。其实这题就是要把permutation的机制搞明白就行了。。。

说说算法:

举个例子:1,3,6,5,4,2

第一步,得到哪里是一直倒序排列的。。。这里面就是6,5,4,2.。。。从3截止

第二步,得到倒序序列里面比3大的最小元素。。

第三步,交换3和那个元素。。

第四步,将新的逆序序列,reverse


当然如果一开始就没有逆序,比如1,3,4,5,2,6,那直接交换2,6就行。。。这里第一步得到的逆序序列就只有6。。从2截止。

第二部得到比2大的最小元素,其实也是唯一元素就是6,

第三步,交换2,6

第四步,reverse新的逆序序列。。即reverse 2没有任何变化


代码如下:

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值