Next Permutation

本文详细阐述了如何实现下一个排列算法,通过从后向前遍历数组,找到第一个需要交换的元素,然后进行交换和排序,以获得数组的下一个字典序排列。包括实例解析与代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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

方法

从后往前。找到第一个i的值比i+1值小的位置。
寻找i以后比i大的最小的数,和i交换。

将i以后的数从小到大排序。
    public void nextPermutation(int[] num) {
        if (num != null && num.length != 0 && num.length != 1) {
            int len = num.length;
            int i = len;
            for (; i > 1; i--) {
                if (num[i - 1] > num[i - 2]) {
                	
                	int flag = 0;
                	
                	for (int k = i - 1; k < len; k++) {
                		if (num[k] <= num[i - 2]) {
                			flag = k - 1;
                			break;
                		}
                	}
                	if (flag == 0) {
                		flag = len - 1;
                	}
                	int temp = num[flag];
                	num[flag] = num[i - 2];
                	num[i - 2] = temp;
                	Arrays.sort(num, i - 1, len);
                	break;
                }              
            }
            if (i == 1) {
                for (int k = 0; k < len / 2; k++) {
                    int temp = num[k];
                    num[k] = num[len - 1 - k];
                    num[len - 1 - k] = temp;
                }
            }
        }
    }


转载于:https://www.cnblogs.com/mengfanrong/p/5236126.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值