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, 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

这篇博客作者讲的比较详细,我是参考的他的:https://yq.aliyun.com/articles/863#

题目大意:

是数学中的排列组合,比如“1,2,3”的全排列,依次是:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

所以题目的意思是,从上面的某一行重排到期下一行,如果已经是最后一行了,则重排成第一行。

但是也不能根据给出的数组中的数字列出所有排列,因为要求不能占用额外的空间。

分析

网上看来一个示例,觉得挺好的,也没必要另外找一个了。

6 5 4 8 7 5 1

一开始没看对方的后面介绍,就自己在想这个排列的下一个排列是怎样的。

首先肯定从后面开始看,1和5调换了没有用。

7、5和1调换了也没有效果,因此而发现了8、7、5、1是递减的。

如果想要找到下一个排列,找到递增的位置是关键。

因为在这里才可以使其增长得更大。

于是找到了4,显而易见4过了是5而不是8或者7更不是1。

因此就需要找出比4大但在这些大数里面最小的值,并将其两者调换。

那么整个排列就成了:6 5 5 8 7 4 1

然而最后一步将后面的8 7 4 1做一个递增。
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        //例子6 5 4 8 7 5 1 
        //首先找到递增的下标值
        int index = nums.size() -1;
        while(index > 0){
             if(nums[index] > nums[index - 1]){
                break;
             }
            index--;
        }//此时的index指向要交换节点的下一个节点8
        if(index == 0){
            //已经是排列的最后一项,返回排列组合第一个
            sort(nums.begin(),nums.end());
            return ;
        }
 
        
        int exchangeIndex;
        for(int i = nums.size()-1; i >= index; --i){
            if(nums[i] > nums[index-1]){
                //因为8751都是递减,所以第一个大于4且最小的值是5;
                exchangeIndex = i;
                break;
            }
        }
        swap(nums[index-1],nums[exchangeIndex]);
        //最后将8741做一个递增
        sort(nums.begin()+index, nums.end());
    }
};
leetcode编译通过.

猜你喜欢

转载自blog.csdn.net/mmshixing/article/details/52154976