LeetCode-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

大概意思就是求一组数按字典排列的下一个顺序,这里不允许使用额外空间(要不然可以直接全排列)

字典排序值安字母或数字从大到小排列,比如说1,2,3,4,5->1,2,3,5,4->1,2,4,3,5->1,2,4,5,3-> ... -> 5,4,3,2,1

现在用int[] a = {1,3,4,5,2}做实例

这里的解决步骤是:

1.从后往前找到一个降序排列,将较小的下标设为i,如在a中为a[2]=4,i为2。

2.从后往前找一个比a[i]大的数a[j],这里为a[3]=5,即j=3.

3.交换下标为i和下标为j的数位置,这里也就是交换a[2]和a[3],得到:a={1,3,5,4,2}

4.对i之后的数字进行排序,这里i=2,也就是对a[2]之后的数字进行排序,得到:a={1,3,5,2,4}

原因暂时没想到

code:

package alivebao;

import java.util.Arrays;

/**
 * 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
 * 
 * @author Administrator
 * 
 */
public class Solution {
	public static void nextPermutation(int[] num) {
		if (num.length <= 1)
			return;
		for (int i = num.length - 2; i >= 0; i--) {
			if (num[i] < num[i + 1]) {
				int j;
				for (j = num.length - 1; j >= i; j--)
					if (num[i] < num[j])
						break;
				// swap the two numbers.
				int temp = num[i];
				num[i] = num[j];
				num[j] = temp;
				// sort the rest of arrays after the swap point.
				Arrays.sort(num, i + 1, num.length);

				for (int z : num)
					System.out.println(z);

				return;
			}
		}
		// reverse the arrays.
		for (int i = 0; i < num.length / 2; i++) {
			int tmp = num[i];
			num[i] = num[num.length - i - 1];
			num[num.length - i - 1] = tmp;
		}
		for (int i : num)
			System.out.println(i);
		return;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] num = { 1, 4, 3, 5, 2 };
		nextPermutation(num);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值