• 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

    这个最开始我比较不能理解题目的意思,后来才明白表示两个排序之间没有其他的排序的意思是,比如1,2,3,4下一个排序是1,2,4,3 --> 1,3,2,4 --> 1,3,4,2 --> 1,4,2,3 -->.....

    就是说第二个排序组成的连续数字,比前面的大,并且中间没有其他的组合,如果已经是4,3,2,1了,那么下一个就是1,2,3,4即回到开头。

    我们来研究一下上面[1,2,3,4]的排序过程,比如比1,2,3,4大的是1,2,4,3怎么出来的呢?再看看1,3,4,2 ---> 1,4,2,3 

    1.找到nums[i] > nums[i-1]

    2.找出i-nums.size()-1之间比nums[i-1]大的最小值,交换这个值与nums[i-1]

    3.对i-1到nums.size()-1之间的元素进行排序

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int end = nums.size()-1;
            while( end > 0 ){
                if( nums[end] > nums[end-1] ){
                    break;
                }
                else{
                    end--;
                }
            }
            if( end == 0 ){
                sort(nums.begin(),nums.end());
            }
            else{
                int min = nums[end];
                int index = end;
                for( int i = nums.size()-1; i > end; i-- ){
                    if( nums[i] < min && nums[i] > nums[end-1] ){
                    min = nums[i];
                    index = i;
                    }
                }
                swap(nums[index],nums[end-1]);
                sort(nums.begin()+end,nums.end());
            }
        }
    };
    

      

  • 相关阅读:
    opencv4.6.0 + rtx2070 + ubuntu16.04 install tutorial AHU
    AcWing 1321. 取石子
    POJ1704 Georgia and Bob(阶梯博弈)
    HDU2188 悼念512汶川大地震遇难同胞——选拔志愿者
    HDU 1730 Northcott Game
    HDU 1846 Brave Game
    HDU 2176 取(m堆)石子游戏
    HDU 1850 Being a Good Boy in Spring Festival
    AcWing 1319. 移棋子游戏
    HDU 1847 Good Luck in CET4 Everybody!
  • 原文地址:https://www.cnblogs.com/rockwall/p/5762377.html
Copyright © 2020-2023  润新知