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());     
        }
    };
  • 相关阅读:
    springboot、监听器
    springboot、拦截器
    Thymeleaf模板引擎
    springboot-banner.txt
    springboot,swagger2
    springboot 热部署
    判断是否为微信环境下打开的网页
    后台接收json数据
    ios 面试题
    iOS 适配问题
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4283610.html
Copyright © 2011-2022 走看看