【LeetCode】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,31,3,2
3,2,11,2,3
1,1,51,5,1

原题的大概意思是:给出一个整型数组,使用全排列,全排列的方法为字典序法,让你找出当前顺序的下一个排序组合。不能额外的去分配内存。

首先得明白全排列按字典序法的含义。假设“123”,全排列有6种组合,字典查找时,先找数小的,也就是“1”,然后“2”,“3”,找到“123”;接下来,哪个组合离“123”更近,那肯定是“132”。依次“213”、“231”、“312”、“321”。

理解了字典序法的含义,接下来再举一个更长的数组

序列: 1 2 5 4 3 1
下一次序列:1 3 1 2 4 5

方法:首先,我们需要从后往前找,去找到一个饱和点,饱和点以后已经是最大的一种情况,例如此例,2比5小,所以认为2为饱和点,2以后已经是降序排列了,可以理解为是20000中最大的数了,再大肯定要超过29999。所以我们需要去找到一个最接近的且比2大的数。再从后往前找,我们找到3,那30000~399999肯定比其他数(大于2)更接近,所以交换2和3的位置。此时得到序列“1 3 5 4 2 1”。3后的“5 4 2 1”依旧是一个降序,那如何再去找到离30000最近的数呢?那肯定是从后往前的数字,也就是1 2 4 5,可以将3后面的数字进行逆转得到。这样就生成了下一个全排列的序列数组。

1->2->5->4->3->1
1->3->5->4->2->1
1->3->1->2->4->5

Java程序代码:

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

另外本人在Github上也有一个关于LeetCode的项目,(一些已做题目的源代码也附上了一些注释),希望得到Star,Github链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值