排列

作者: 我是谁的小超人 | 来源:发表于2018-03-16 16:48 被阅读0次

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

【解法】
step1:从它的最后一个元素开始,向从后向前遍历,找到第一个满足nums[index] < nums[index+1]的索引index。因此,从nums[index+1, n-1]的元素是反向排序的。
(例如原始号码135421,nums[index] = 3,nums[index+1, n-1] 值为5421,是反向排序。)

step2:为了找到下一个排列,我们必须增大nums[index]的值,同时为了使增加的量最小化,将它与num[index+1, n-1]之间的大于nums[index]的最小值交换。
(nums[index] = 3,nums[index+1, n-1]之间的大于nums[index]的最小值是4,所以交换这两个数字,变为145321。)

step3:最后一步是使num[index+1, n-1]尽可能小,我们只需要逆向排序num[index+1, n-1]。
(num[index+1, n-1]为5321,对其进行逆向排序,为1235,所以最终结果为141235。)

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        if(nums.size()<=1)
            return;
        int index;
        for(index=nums.size()-2; index>=0; --index){
            if(nums[index]<nums[index+1])
                break;
        }
        // 当输入为321时,index此时为-1
        if(index>=0){
            int i = nums.size()-1;
            while(nums[i]<=nums[index])
                --i;
            swap(nums[index], nums[i]);            
        } 
        reverse(nums.begin()+index+1, nums.end());
    }
};

相关文章

  • 排列类算法问题大总结

    全排列 带重复元素的排列 下一个排列 上一个排列 第 k 个排列 排列序号 排列序号II 全排列 给定一个数字列表...

  • 排列组合——排列

    学习概率论与数理统计,要用到排列组合的知识,更重要的是要用到排列组合的思维方法,因此,学习概率与统计是很有必要了解...

  • 时间长了就生疏的排列组合

    排列数:组合数:全排列:排列是先组合再排列: 最基本的排列组合公式,不能忘在脑后,应该熟稔于心。 排列和组合的区...

  • 排列

    窗前的人打开电脑,戴上耳机,打开台灯,关上了房间的灯光。 屋内冷气的声音慢慢隐去了,他不经意间看见一张报纸。报纸上...

  • 排列

    Next Permutation Implement next permutation, which rearra...

  • 排列

    主副:千日红 副:油菜花 中间枝:小菊花,高山羊齿 剑山的摆放中间的位置可以依靠任意一边近一些 副枝和另外两个副助...

  • 排列

    上述代码中列出了 全排列的非递归、递归解法 从n个数中取m个的各种排列形式输出

  • 排列

    排列 a,b,c的排列形式有abc,acb,bac,bca,cab,cba,六种排列方式。 采用递归的方法来实现排...

  • 排列

  • 排列

    用小积木摆成一形状: 数学棒: 整体示意图:

网友评论

      本文标题:排列

      本文链接:https://www.haomeiwen.com/subject/eikrqftx.html