[leetcode刷题系列]Next Permutation

应该算经典问题了。 解法就是从后往前找到第一个小于它后面的那个数。记录下他的位置p,然后再从后往前中第一个大于位置p上面的数的数的位置,记录为first。

然后交换p和first上面的数字,并将位置p以后的序列反转就可以了。

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(num.size() <= 1)
            return ;
        int p = num.size() - 2;
        while(p >= 0 && num[p] >= num[p + 1])
            p --;
        if(p < 0){
            reverse(num.begin(), num.end());
            return ;
        }
        for(int i = num.size() - 1; i >= p + 1; -- i)
            if(num[i] > num[p]){
                swap(num[i], num[p]);
                reverse(num.begin() + p + 1, num.end());
                return;
            }
    }
};


你可能感兴趣的:([leetcode刷题系列]Next Permutation)