码迷,mamicode.com
首页 > 其他好文 > 详细

31. Next Permutation

时间:2017-06-07 23:15:17      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:vector   stl   inpu   logs   on()   asc   难度   ble   gre   

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()算法,可以实现本功能。当然,本题要求读者手动实现,其实难度不小,但是如果想通了就很简单。

首排列是彻底的顺序,尾排列是彻底的逆序。假设前一个排列是P,后一个排列是Q。那么会有P和Q的相同前缀的长度尽可能的长。

对于一个数组1,2,5,4,3,1,它的下一个排列是1,3,1,2,4,5

因此,我们可以总结出如下规律:

从后往前看,数字应当是逐渐增大的,如上例中,增大的趋势直到2才停止,这时应当从后往前寻找第一个比2大的数也就是3。交换2和3以后,显然,该位置以后的数是逆序排序,为了使这部分的数尽可能的小,因此要逆转这部分数组。

lass Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size();
        if (n <= 1)
            return;
        
        int i = n - 1;
        while (i != 0 && nums[i] <= nums[i - 1])
            --i;
            
        if (i == 0) {
            std::reverse(nums.begin(), nums.end());
            return;
        }
        
        --i;
        int j = n - 1;
        for (; nums[j] <= nums[i]; --j) {}
        std::swap(nums[i], nums[j]);
        std::reverse(nums.begin() + i + 1, nums.end());
        return;
    }
};

 

31. Next Permutation

标签:vector   stl   inpu   logs   on()   asc   难度   ble   gre   

原文地址:http://www.cnblogs.com/naivecoder/p/6959295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!