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

    class Solution {
    public:
        void nextPermutation(vector<int> &num) {
            // Note: The Solution object is instantiated only once and is reused by each test case.
            for(int i=num.size()-2;i>=0;i--){
                if(num[i]<num[i+1]){
                    //from i to end
                    //eg. 1243 
                    //first find 243 then find the next value bigger than 2,swap it with 2 and sort then we get 324
                    vector<int> one;
                    int ptr=i+1;
                    for(int j=i+2;j<num.size();j++){
                        if(num[j]>num[i]&&num[j]<num[ptr]){
                            ptr=j;
                        }
                    }
                    int temp=num[i];
                    num[i]=num[ptr];
                    num[ptr]=temp;
                    for(int j=i+1;j<num.size();j++)
                    one.push_back(num[j]);
                    sort(one.begin(),one.end());
                    for(int j=0;j<one.size();j++){
                        num[i+1+j]=one[j];
                    }
                    return;
                }
            }
            sort(num.begin(),num.end());
        }
    };
  • 相关阅读:
    顧客満足度調査
    GeoStTool.dll过滤图层
    GeoStTool.ini相关技术要点
    GeoStTool.dll与RasterServer通信
    hdu 1007 Quoit Design
    hdu 4325 Flowers
    hdu 2516 取石子游戏
    hdu 1006 Tick and Tick
    CodeForces 101A Homework
    ZOJ Problem Set 1879
  • 原文地址:https://www.cnblogs.com/superzrx/p/3353437.html
Copyright © 2011-2022 走看看