• next permutaion算法


    算法描述:
    Find largest index i such that array[i − 1] < array[i].

    Find largest index j such that j ≥ i and array[j] > array[i − 1].

    Swap array[j] and array[i − 1].

    Reverse the suffix starting at array[i].

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    class Solution {
    public:
    //    void nextPermutation(vector<int>& nums) {
    //        //find the fisrt non-increacing number from the end
    //        if(nums.size() < 2) return;
    //        vector<int>::reverse_iterator it = nums.rbegin();
    //        while((it+1) != nums.rend() && *(it+1) >= *it) it++;
    //        if(it+1 == nums.rend()){
    //            reverse(nums.begin(), nums.end());
    //        }
    //        else{
    //            //find the min number greater than *(it + 1)
    //            vector<int>::reverse_iterator itb = it+1;
    //            vector<int>::reverse_iterator ite = nums.rbegin();
    //            while(ite != itb && *ite <= *itb) ite++;
    //            int temp = *ite;
    //            *ite = *itb;
    //            *itb = temp;
    //            reverse(nums.rbegin(), itb);
    //        }
    //    }
    
        void nextPermutation(vector<int>& nums) {
            if(nums.size() < 2) return;
            int pos = nums.size();
            while(--pos > 0){
                if(nums[pos] > nums[pos - 1]){
                    int pivot = pos -1;
                    int back = nums.size();
                    while(nums[--back] <= nums[pivot]){};
                    swap(nums[pivot], nums[back]);
                    break;
                }
            }
            reverse(nums.begin()+pos,nums.end());
        }
    };
    
  • 相关阅读:
    跨域资源共享 CORS 详解
    C# 每月第一天和最后一天
    jexus http to https
    ASP.NET MVC 路由学习
    jexus
    centos7 添加开机启动项
    jexus docker
    HTTP2.0新特性
    jexus配置支持Owin
    Autofac Named命名和Key Service服务
  • 原文地址:https://www.cnblogs.com/shaolw/p/5593585.html
Copyright © 2020-2023  润新知