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)]);
            } } }
  • 相关阅读:
    C# 获取程序当前路径
    主线程等待子线程执行二
    ADO.NET Entity Framework Code Fisrt 开篇(一)
    解决Eclipse java was started but returned exit code = 1问题
    windows 下YII框架初试
    hadoop的partitioner
    YII 学习一: YII 初试
    linux 文件大小ll和du不一致问题
    [转载]PyDev for Eclipse 简介
    python 常用代码学习笔记之commands模块
  • 原文地址:https://www.cnblogs.com/weiyi-mgh/p/6833128.html
Copyright © 2011-2022 走看看