LeetCode 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

Subscribe to see which companies asked this question.
题目意思就是让你输出这个数列的下一个字典序大的排列, 如果它本身最大的话,输出最小的那个。

  • 检查一个是否本身最大, 不是的话直接next_permutation()。
  • 是的话直接把vector反转一下就是最小的了
class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        bool is = false;
        size_t sum = nums.size();
        for(size_t i = 0; i < sum-1; ++ i)
            if(nums[i] < nums[i+1])
                is = true;
        if(is)
            next_permutation(nums.begin(), nums.end());
        else
        {
            size_t b = 0, e = sum - 1;
            while(b < e)
                swap(nums[b++], nums[e--]);
        }
    }
};
posted @ 2017-03-19 20:20  aiterator  阅读(102)  评论(0编辑  收藏  举报