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());
            }
        }
    };
  • 相关阅读:
    bzoj 1031: [JSOI2007]字符加密Cipher
    python re模块实现计算器
    python sys模块和序列化模块
    python time时间模块
    python 发红包的小程序
    python ranndom模块及生成验证码
    python os模块练习题
    python os模块常用命令
    快速排序,归并排序
    选择排序和插入排序
  • 原文地址:https://www.cnblogs.com/zengzy/p/4964207.html
Copyright © 2011-2022 走看看