zoukankan      html  css  js  c++  java
  • 31. Next Permutation (Array; Math)

    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

    思路:对大小的影响尽可能小=>影响尽可能右侧的位=>右向左扫描,找到第一个<右侧的数(i)

    将右边最小的>nums[i]的数(j)与它交换

    从小到大排列i之后的数

    规律:

    1. 总是最后一个数与之前比它小的最近的那个数交换

    2. 如果没有,则看倒数第二个数,以此类推

    3. 如果都没有,则返回递增序列

    第1、2种情况,两个swap的数之间的数要按从小到大排列

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int size = nums.size();
            int swapIndex = size, tmp, i ,j;
            
            for(i = size-2; i >= 0; i--){
                for(j = i+1; j < size; j++){
                    if(nums[j] <= nums[i] || (swapIndex<size && nums[j]>=nums[swapIndex])) continue;
                    swapIndex = j;
                }
                if(swapIndex>=size) continue;
                tmp = nums[i];
                nums[i]=nums[swapIndex];
                nums[swapIndex]=tmp;
                sort(nums.begin()+i+1, nums.end());
                break;
            }
            if(i<0){
                sort(nums.begin(), nums.end());
            }
        }
    };
  • 相关阅读:
    还零钱
    递归与动态规划II-汉诺塔
    leetcode 95. Unique Binary Search Trees II
    技术实力详解
    正反向路由
    usermod命令、用户密码管理、mkpasswd命令
    作为阿里的面试官,我有话想说。
    [招聘] 阿里巴巴-淘系技术部,长期内推,专人跟进。
    Vue源码翻译之渲染逻辑链
    Vue源码翻译之组件初始化。
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4855323.html
Copyright © 2011-2022 走看看