zoukankan      html  css  js  c++  java
  • 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

    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
        int i=0,j=0,k=0;
        int n=num.size();
        if (n==0||n==1)return;
        if(n==2)
        {
           reverse(num.begin(),num.end());
           return;
        }
        int jj=0;
        for(;jj<num.size()-1;jj++)
        {
            if (num[jj]<num[jj+1])
            {
                break;
            }
        }
        if(jj==num.size()-1)
        {
            reverse(num.begin(),num.end());
            return;
        }
        for (j=num.size()-2;j>=0;j--)
        {
            if(num[j]<num[j+1])break;
        }
        i=j+1;
        for (k=num.size()-1;k>=0;k--)
        {
            if(num[i-1]<num[k])break;
        }
        j=k;
        int temp=num[i-1];
        num[i-1]=num[j];
        num[j]=temp;
        reverse(num.begin()+i,num.end());     
        }
    };
  • 相关阅读:
    PHP对象
    MySQL多表更新
    使用not in的子查询
    MySQL比较运算符的子查询
    控制器调用函数
    MVC目录规范
    MVC流程
    mxnet安装
    离线安装Python包hickle,easydict
    深度学习基础
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283610.html
Copyright © 2011-2022 走看看