next permutation函数

介绍:

给定一个排列好的数字数组,这些数字的所有排列组合组成的数组的有序集合中,求给定数组所在集合中的位置的下一个数组(若已到最后一个数组,下一个数组为第一个数组)

 

算法步骤:

1.从右到左进行扫描,发现第一个违背递增趋势的数字,称之为 PartitionNumber

2.从右到左进行扫描,发现第一个比 PartitionNumber 要大的数,称之为 ChangeNumber

3.交换 PartitionNumberChangeNumber

4.反转在 PartitionNumber 右侧的数


代码:

public class Solution {
    public static void main(String[] args) throws Exception {
        int[] nums = {3, 2, 1};
        nextPermutation(nums);
        for (int i : nums)
            System.out.print(i + "\t");
    }


    public static void nextPermutation(int[] nums) {
        int partitionNumber = 0;
        int changeNumber = 0;
        // 1.find partitionNumber
        for (int index = nums.length - 1; index > 0; index--) {
            if (nums[index - 1] < nums[index]) {
                partitionNumber = index - 1;
                break;
            }
        }
        // 2.find changeNumber
        for (int index = nums.length - 1; index >= 0; index--) {
            if (nums[index] > nums[partitionNumber]) {
                changeNumber = index;
                break;
            }
        }
        // 3.swap partitionNumber and changeNumber
        if (partitionNumber == 0 && changeNumber == 0) {
            reverse(nums, 0, nums.length - 1);
            return;
        }
        swap(nums, partitionNumber, changeNumber);
        // 4.resverse all right num
        reverse(nums, partitionNumber + 1, nums.length - 1);
    }

    private static void reverse(int[] nums, int l, int r) {
        while (l < r) {
            swap(nums, l++, r--);
        }
    }

    private static void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

}

 

参考文章:

实现next_permutation函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值