zoukankan      html  css  js  c++  java
  • [leetcode]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. 下个排列是全部比当前排列大的中最小的那个

    要实现这个有三个步骤:

    1. 我们要找增大哪一位才干使排列增大。
    2. 这一位增大到多少才干使增大的最少。
    3. 其它低位的排列怎么处理。

    从低位依次比較A[i-1]与A[i],找到第一个A[i-1] <A[i] 交换A[i-1] 与其后大于A[i-1]的某位能够实现排列的增大。

    在A[i-1]之后的低位找到比A[i-1]大的最小的A[j],交换A[i-1]和A[j].

    交换了A[i-1]和A[j],就保证了排列会增大。对于A[i-1]后面的内容,进行从小到大排序就能够了。


    代码:

    void nextPermutation(vector<int> &num) {  //C++
            for(int i = num.size()-1; i > 0 ; i-- )
            {
                    if(num[i] > num[i-1])
                    {
                        int min = num[i] - num[i-1];
                        int pos = i;
                        for(int k = i+1; k <num.size(); k++)
                        {
                            if(num[k] - num[i-1] < min && num[k] - num[i-1] >0)
                            {
                                min = num[k] - num[i-1];
                                pos  = k;
                            }
                        }
                        int tmp = num[pos];
                        num[pos] = num[i-1];
                        num[i-1] = tmp;
                        sort(num.begin()+i,num.end());
                        return;
                    }
            }
            
            sort(num.begin(),num.end());
        }


  • 相关阅读:
    Cron表达式,springboot定时任务
    go 语言中windows Linux 交叉编译
    SSM框架处理跨域问题
    golang gin解决跨域访问
    关于Integer类的值使用==比较
    IoC注解
    spring基础知识
    SQL SERVER大话存储结构(3)_数据行的行结构
    SQL SERVER
    MySQL-记一次备份失败的排查过程
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4212848.html
Copyright © 2011-2022 走看看