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 and use only constant 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

一开始无从下手,因为不理解题目要干啥。然后查资料:

next_permutation函数将按字母表顺序生成给定序列的下一个较大的排列,直到整个序列为降序为止。prev_permutation函数与之相反,是生成给定序列的上一个较小的排列。二者原理相同,仅遍例顺序相反

 

 

 

 

 

问题:如何求一个数组的下一个排列?

 

 

 

假设该数组为3 6 4 2.下一个排列应为 4 2 3 6.

 

过程:对于一个任意序列,最小的排列是增序,最大的为减序。

 

从最后一位向前看,首先得到的是2,单纯的一个数不需要进行交换。

 

然后得到的是 4 2,4大于2,在这个子序列中已经为最大序列,无法排出更大的序列了。

 

然后得到的是 6 4 2,原理同上。

 

之后得到的是 3 6 4 2,此时由于3小于6且小于4,而 3 6 4 2的下一个排列应为比3 6 4 2这个排列大的排列中最小的那个,所以3应该和4进行交换,此时该排列变为 4 6 3 2.此时4位于首端,所以之后的序列应为最小序列,即 2 3 6.综上,最终结果应为 4 2 3 6.

--------------------- 

作者:HyJoker 

来源:CSDN 

原文:https://blog.csdn.net/hyjoker/article/details/50899362 

版权声明:本文为博主原创文章,转载请附上博文链接!

好的,现在已经有点明白了。

至此,可以写code了

 

class Solution {
    public void nextPermutation(int[] nums) {
        if(nums==null || nums.length==0) return;
        int i = nums.length-2;
        while(i>=0&&nums[i] >= nums[i+1])
            i--;
        if(i>=0){
        int j = i + 1;
        while(j < nums.length && nums[j] > nums[i])
            j++;
        j--;
        swap(nums,i,j);       
        }
         reverse(nums,i+1,nums.length-1);
    }
    public void swap(int[] nums, int i, int j){
        int t = nums[i];
        nums[i] = nums[j];
        nums[j] = t;
    }
    public void reverse(int[] nums, int i, int j){
        while(i<j){
            swap(nums, i++, j--);
        }
    }
}

 

转载于:https://www.cnblogs.com/wentiliangkaihua/p/10416223.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值