[Leetcode] Next Permutation

Next Permutation Feb 25 '12 4235 / 11932

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> &num) {
        int len = num.size();
        for (int i = len - 1; i > 0; i--) {
            if (num[i] > num[i-1]) {
                int j = len - 1;
                while (j > i - 1 && num[i-1] >= num[j]) j--;
                swap(num[i-1], num[j]);
                sort(num.begin() + i , num.end());
                return;
            }
        }
        sort(num.begin(), num.end());
    }
};

猜你喜欢

转载自cozilla.iteye.com/blog/1925906
今日推荐