zoukankan      html  css  js  c++  java
  • leetcode problem 31 -- 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

    代码:

    class Solution {
    public:
        void nextPermutation(vector<int> &v) {
            int left = findIncFromRight(v);
            if (left != -1) {
                int right = findMinGreater(v, left); 
                swap(v[left], v[right]);
            }
            reverse(v.begin() + left + 1, v.end());
        }
    
    private:
        int findIncFromRight(vector<int> &v) {
            int i;
            for (i = v.size()-1; i > 0; --i) {
                if (v[i-1] < v[i])
                    break;
            }
            return i - 1;
        }
    
        int findMinGreater(vector<int>& v, int left) {
            int i; 
            for (i = left+1; i < v.size(); ++i) {
                if (v[left] >= v[i])
                    break;
            }
            return i-1;
        }
    };
  • 相关阅读:
    排座椅
    关于math.h的问题
    客户调查
    排队打水
    删数游戏
    小数背包
    零件分组
    桐桐的组合
    桐桐的数学游戏
    桐桐的全排列
  • 原文地址:https://www.cnblogs.com/lysuns/p/4442015.html
Copyright © 2011-2022 走看看