zoukankan      html  css  js  c++  java
  • 【leetcode】Next Permutation

    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

     
     
    先从后往前寻找,找到首次下降的位置i      (找到进位的位置)
    从位置i开始,往后寻找,找到第一个小于等于num[i]的位置j,  交换i和j-1(找到进位后,最高位的值)
    将i+1后面的元素逆序排列 (取最小)
     
    用一个例子来说明,比如排列是(2,3,6,5,4,1),求下一个排列的基本步骤是这样:
    1) 先从后往前找到第一个不是依次增长的数,记录下位置p。比如例子中的3,对应的位置是1;
    2) 接下来分两种情况:
        (1) 如果上面的数字都是依次增长的,那么说明这是最后一个排列,下一个就是第一个,其实把所有数字反转过来即可(比如(6,5,4,3,2,1)下一个是(1,2,3,4,5,6));
        (2) 否则,如果p存在,从p开始往后找,找到下一个数就比p对应的数小的数字,然后两个调换位置,比如例子中的4。调换位置后得到(2,4,6,5,3,1)。最后把p之后的所有数字倒序,比如例子中得到(2,4,1,3,5,6), 这个即是要求的下一个排列。

    以上方法中,最坏情况需要扫描数组三次,所以时间复杂度是O(3*n)=O(n),空间复杂度是O(1)。代码如下:

     
     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4        
     5         int n=num.size();
     6         int i,j;
     7         for(i=n-2;i>=0;i--)
     8         {
     9             if(num[i]<num[i+1])
    10             {
    11                 break;
    12             }
    13         }
    14         if(i>=0)
    15         {
    16             for(j=i+1;j<n;j++)
    17             {
    18                 if(num[j]<=num[i])
    19                 {
    20                     break;
    21                 }
    22             }
    23             j--;
    24             swap(num[i],num[j]);
    25         }
    26        
    27         reverse(num.begin()+i+1,num.end());
    28     }
    29    
    30    
    31     void swap(int &a,int &b)
    32     {
    33         int tmp=a;
    34         a=b;
    35         b=tmp;
    36     }
    37 };
  • 相关阅读:
    基本sql查询语句练习
    SZU:J38 Number Base Conversion
    SZU:B54 Dual Palindromes
    SZU:A66 Plastic Digits
    HOJ:2031 进制转换
    SZU:G34 Love code
    SZU:A25 Favorite Number
    Vijos:P1001谁拿了最多奖学金
    SZU:A26 Anagram
    SZU:A12 Jumping up and down
  • 原文地址:https://www.cnblogs.com/reachteam/p/4214181.html
Copyright © 2011-2022 走看看