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);
        }
    };
    

      

  • 相关阅读:
    POJ--2356 Find a multiple
    Trailing Zeroes (III)
    第一章 快速入门
    第二章 变量和基本类型
    第三章 标准库类型
    第四章 数组和指针
    第五章 表达式
    第六章 语句
    第七章 函数
    第八章 标准IO库
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3445102.html
Copyright © 2011-2022 走看看