zoukankan      html  css  js  c++  java
  • 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中有个一个现成的算法,基本思路就是从后往前找到最大的排列a[i] a[i+1] ...a[n] ,什么是最大的排列呢,假设排列a0 a1 a2 a3 a4 a5,如果ao<a1 && a1 >=  a2 >= a3 >= a4 >=a5,那么a1 a2 a3 a4 a5就是最大的排列。同时最大排列代表的含义就是,以a[i-1]开头的排列已经排完了,下一个排列应该是从a[i] a[i+1]..a[n]中找到最小的大于a[i-1]的数,然后把其与a[i-1]交换一下,再把a[i] a[i+1]..a[n]反转就可以了。

    class Solution {
    public:
        void nextPermutation(vector<int>& nums) {
            int numsSize = nums.size();
            int i=numsSize-1,j=i-1;
            while(j>=0 && nums[i]<= nums[j]){
                i=j;j-=1;
            }
            i = numsSize-1;
            cout<<"j="<<j<<endl;
            while(j>=0 && i>=0 && nums[i]<= nums[j]){
                i--;
            }
            cout<<"i="<<i<<endl;
            if(j>=0){
                swap(nums[i],nums[j]);
                reverse(nums.begin()+j+1,nums.end());
            }else{
                reverse(nums.begin(),nums.end());
            }
        }
    };
  • 相关阅读:
    数据结构-索引
    CAS自旋volatile变量
    深入理解AQS
    EL表达式
    JSTL 核心标签库 使用
    JSP 九个隐含JSP对象
    jsp基本语法总结
    Commons FileUpLoad 两种上传方式解
    Servlet 异常处理
    Servlet 过滤器 Filter
  • 原文地址:https://www.cnblogs.com/zengzy/p/4964207.html
Copyright © 2011-2022 走看看