[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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

这个题目是实现STL算法next_permutation,如果只要过这个题目,直接调用即可,但也可以自己简易实现之

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        next_permutation(num.begin(), num.end());
    }
};

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        if(num.empty() || num.size() == 1) return;
        int first = 0, last = num.size();
        int i = last - 1;
        while(1)
        {
            int ii = i--;
            if(num[i] < num[ii])
            {
                int j = last;
                while(num[--j] <= num[i]);
                swap(num[i], num[j]);
                reverse(num.begin() + ii, num.end());
                return;
            }
            if(i == 0)
            {
                reverse(num.begin(), num.end());
                return;
            }
        }
    }
};


你可能感兴趣的:([LeetCode] Next Permutation)