zoukankan      html  css  js  c++  java
  • leetcode: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,31,3,2
    3,2,11,2,3
    1,1,51,5,1

    看到此题,有点摸不着头脑,但是稍作分析,发现是有规律的。思路分析如下

    其实给定一串数字,其排列:a0,a1,a2,……,an-2,an-1,总存在这样三种情况:

    ①、这个降序排列: a0>a1>a2>……>an-2>an-1  显然,就是最大的一个排列序列,从前往后元素翻转排列成为最小的一个排列;

    ②、前面无所谓,最后面是升序排列: ……<an-2<an-1  这个只需要最后这两个元素交换位置就可以了,即成下一个排列;

    ③、前面有升序,最后面是降序排列: ……ai-1<ai>ai+1>……>an-2>an-1  这种情况需要首先找到从ai开始最小的大于ai-1的元素,并与ai-1交换,然后再把ai到an-1 翻转
    成递增序列。

    实现代码:

    void nextPermutation(vector<int>& nums) {
            if(nums.size() <= 1)
             {
          
    return ;
          }
    int len=nums.size(); int i=len-1; while(i>0 && nums[i]<=nums[i-1]) {
          
    --i;
          }
    if(i==0) { for(int j=0;j<len/2;++j)
            { swap(nums[j], nums[len
    -1-j]);
            } }
    else if(i==len-1) {
           swap(nums[i],nums[i
    -1]);
          }
    else { int index=i; while(index<len && nums[index]>nums[i-1]) {
            
    ++index;
            }
    --index; swap(nums[i-1],nums[index]); for(int j=i;j<i+(len-i)/2;++j) {
             swap(nums[j], nums[len
    -1-(j-i)]);
            } } }
  • 相关阅读:
    点击button先执行js在执行后台代码客户端判断控件是否为空
    VNC远程登录端使用经验之一
    TB平台搭建之一
    能力不足之 根据时序图转化为Verilog代码
    Verilog之语句位置
    verilog 1995 VS 2001 part1模块声明的扩展
    verilog $fopen 函数的小缺陷
    tab key usage
    poj2184 Cow Exhibition
    hdu2546 饭卡
  • 原文地址:https://www.cnblogs.com/weiyi-mgh/p/6833128.html
Copyright © 2011-2022 走看看