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

    思考:全排列的非递归函数。

    class Solution {
    public:
        void Reverse(vector<int> &num,int begin,int end)
        {
            while(begin<end)
            {
                swap(num[begin++],num[end--]);
            }
        }
        void nextPermutation(vector<int> &num) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int len=num.size();
            if(len==0||len==1) return;
            int i,j;
            for(i=len-2;i>=0;i--)
            {
                if(num[i]<num[i+1])
                {
                   for(j=len-1;j>i;j--)
                   {
                       if(num[j]>num[i])
                       {
                           swap(num[i],num[j]);
                           Reverse(num,i+1,len-1);
                           return;
                       }
                   }
                }
            }
            Reverse(num,0,len-1);
        }
    };
    

      

  • 相关阅读:
    副本集-Replica Sets
    SpringBoot整合SpringData MongoDB
    Auth认证
    Form
    flask一些插件
    SQLAlchemy
    session
    上下文
    flask路由
    Flask中间件
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3445102.html
Copyright © 2011-2022 走看看