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,3→1,3,2
    3,2,1→1,2,3
    1,1,5→1,5,1

    题意:给定序列,返回其全排列的下一个排列。

    思路:这里给出C++ STL中next_permutation函数的实现原理。从后往前遍历数组,找到第一对降序的位置(即,num[i] <num[i+1],如果正着看是升序),记下位置,然后重新从后向前(到 i 之前)遍历数组,找到第一个大于num[ i ]的元素num[ k ],交换num[ i ]和num[ k ],然后将位置 i 之后的元素反转,即得到给定序列的全排列的下一个排列。值得注意一点是,若是找到降序对,说明,这个已经是全排的最后一个,这样只需反转其全部即可。如:

    给定序列:1  2  8  6  5  3

    下一序列:1  3  2  5  6  8

    过程如下:1  2  8  6  5  3,即先找到num[ i ]=2,然后重新从尾到头遍历,

         1  2  8  6  5  3,找到第一大于2的值3,

         1  3  8  6  5  2 ,交换

         1  3  2  5  6  8  完成

    代码如下:

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) 
     4     {
     5         int len=num.size();
     6         if(len<2)   return;
     7         int i=0;
     8         for(i=len-2;i>=0;--i)
     9         {
    10             if(num[i]<num[i+1])
    11                 break;
    12         } 
    13         int k=0;   
    14         for(k=len-1;k>i;--k)
    15         {
    16             if(num[k]>num[i])
    17                 break;
    18         }
    19 
    20         if(i>=0)    //i可能等于-1
    21             swap(num[i],num[k]);
    22         reverse(num.begin()+i+1,num.end());
    23     }
    24 };
  • 相关阅读:
    git 好文引流
    无法访问Swagger 或 druid面板无法访问 #报异常
    MachineLearning入门-7(数据理解)
    MachineLearning入门-6(数据导入)
    MachineLearning入门-5(Python和Scipy简介)
    百度PaddlePaddle入门-10(数据处理)
    百度PaddlePaddle入门-9(建模)
    百度PaddlePaddle入门-8(模型探讨)
    MachineLearning入门-4(理解数据集)
    百度PaddlePaddle入门-7 (Numpy的应用)
  • 原文地址:https://www.cnblogs.com/love-yh/p/7106217.html
Copyright © 2011-2022 走看看