• 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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    感觉又是一道智商题啊,方法比较难以想到,想到后就容易了,没有自己写代码,直接看的网上的答案·················································

    题意寻找比当前排列顺序大的下一个排列。

    1)因为降序序列是没法变的更大的,所以从后往前找到第一个升序对的位置。

    2)然后就存在调整大小排列顺序的可能,从后往前找到比当前位置大的元素,交换之。

    3)当前位置后面的元素还是降序排列,将他们反转得到最小顺序排列。其实就是原来当前位置元素后面是最大的排列,而交换后的新元素之后是最小的排列,他们就是相邻的顺序。

    当不存在升序,则当前排列是最大排列,只要旋转整个序列变成最小排列。

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

      

  • 相关阅读:
    Java uuid生成随机32位
    Java 、C# Excel模板,数据一对多,主从表关系,导入到数据库
    ROS 八叉树地图构建
    操作系统基础信息搜集
    菜鸟的信息安全学习之路
    提权初探
    Windos/Linux 反弹 shell
    初读鸟哥的linux私房菜的收获
    linux中find命令的摘要
    分享一个Flink checkpoint失败的问题和解决办法
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4774229.html
Copyright © 2020-2023  润新知