[LeetCode] 31. Next Permutation ☆☆☆

本文详细介绍了如何实现下一个排列算法,该算法将数组中的数字重新排列为字典序中更大的排列。若当前排列已是最大,则变为最小排列。文章通过示例解释了算法原理,并提供了Java实现代码。

 

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

 

解法:

  这道题要求下一个排列顺序,也就是全排列中的下一个(如:123的全排列为123、132、213、231、312、321,给定其中一个,输出其下一个),如果给定数组是降序,则说明是全排列的最后一种情况,则下一个排列就是最初始情况,全排列知识可以参见:全排列生成算法:next_permutation。我们再来看下面一个例子,有如下的一个数组

1  2  7  4  3  1

下一个排列为:

1  3  1  2  4  7

那么是如何得到的呢,我们通过观察原数组可以发现,如果从末尾往前看,数字逐渐变大,到了2时才减小的,然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可,步骤如下:

1  2  7  4  3  1

1  2  7  4  3  1

1  3  7  4  2  1

1  3  1  2  4  7

public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int index = nums.length - 2;
        for (; index >= 0; index--) {
            if (nums[index] < nums[index + 1]) {
                break;
            }
        }
        if (index == -1) {
            Arrays.sort(nums);
            return;
        }
        
        int biggerIndex = nums.length - 1;
        for (; biggerIndex >= 0; biggerIndex--) {
            if (nums[biggerIndex] > nums[index]) {
                break;
            }
        }
        
        swap(nums, index, biggerIndex);
        reverse(nums, index + 1, nums.length - 1);
    }
    
    public void swap(int[] num, int i, int j) {
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
    
    public void reverse(int[] num, int begin, int end) {
        for (int i = begin, j = end; i < j; i++, j--) {
            swap(num, i, j);
        }
    }
}

 

转载于:https://www.cnblogs.com/strugglion/p/6424191.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值