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 1,2,31,3,2
    2 3,2,11,2,3
    3 1,1,51,5,1

    题解:字典序法

    步骤:

    1.从右向左找出第一个比它右边数字小的数,记为a;

    2.找出a右边比它大的最小的数,记为b;

    3.交换a和b;

    4.reverse原来a所在位置后面所有的元素。

    代码:

     1 class Solution {
     2 public:
     3     void nextPermutation(vector<int> &num) {
     4         int n = num.size();
     5         int j;
     6         for(j = n-2;j >= 0;j --){
     7             if(num[j] < num[j+1])
     8             {
     9                 //与右边比它大的最小的数互相换位
    10                 int min_index = n-1;
    11                 int minmum = 32767;
    12                 for(int u = n-1;u > j;u --)
    13                     if(num[u] > num[j]){
    14                         if(num[u] < minmum){
    15                             min_index = u;
    16                             minmum = num[u];
    17                         }
    18                         break;
    19                     }
    20 
    21                 char temp = num[min_index];
    22                 num[min_index] = num[j];
    23                 num[j] = temp;
    24                 reverse(num.begin()+j+1,num.end());
    25                 break;
    26 
    27             }
    28         }
    29         if(j < 0)
    30             reverse(num.begin(),num.end());
    31     }
    32 };

    有一种类似321这种序列的情况,它的下一个排列是123,字典序法是找不出来的,所以在代码29行单独加了一个判断,如果遇到这样的序列,直接倒置返回就可以了。

  • 相关阅读:
    MSF进程迁移
    中间件漏洞之Nginx
    MSF常用payload生成
    消息中间件的对比
    Jetty简介
    Java中集合转数组,数组转集合
    SpringCloud简介
    码云上添加ssh密匙
    在Dubbo中使用高效的Java序列化(Kryo和FST)
    dubbo-负载均衡
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3696611.html
Copyright © 2011-2022 走看看