一.题目
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 and use only constant 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,23,2,1 → 1,2,31,1,5 → 1,5,1
二.分析过程
对于{1,2,5,4,3}想找下一个比这个序列大的,一定是替换后面的数字,如果替换前面的比如替换1,得到的结果会比这个序列大,但不能满足题目的意思,从后往前找,发现{2,5,4,3}该序列存在满足题目的序列,对于{5,4,3},{4,3}等是不存在的。而要得到next permutation,只需要从{5,4,3}取出比2大的元素中的最小一个替换2,在生成{5,4,2}的最小序列,跟原来的序列合并就得到想要的结果了,有点贪心法的意思,局部的最优解就是整体的最优解
三.代码实现
public class NextPermutation {
public static void nexPermutation(int[] nums) {
int i = nums.length - 1;
//找到含有nexpermutation的子序列
for (; i > 0 && nums[i] <= nums[i - 1]; i--) ;
int start = i -1;
//如果start不为0,说明存在下一个比当前序列大的序列,从后面子序列中找出大于nums[i]的元素最小元素替换他
if (start >= 0) {
int temp = nums[start];
boolean changed = false;
for (int j = i; j < nums.length; j++) {
if (!changed) {
if (nums[j] > nums[start]) {
swap(nums, start, j);
changed = true;
}
} else if (nums[j] > temp && nums[j] < nums[start]) {
swap(nums, start, j);
}
}
}
//生成后面子序列的最小序列
generateMin(nums, i);
}
public static void generateMin(int[] nums, int i) {
for (; i < nums.length - 1; i++) {
for (int n = i + 1; n < nums.length; n++) {
if (nums[i] > nums[n]) {
swap(nums, i, n);
}
}
}
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
public static void main(String[] args) {
int[] nums = {1, 2};
nexPermutation(nums);
Arrays.stream(nums).forEach(t -> {
System.out.println(t);
});
}
}
本文介绍了一个算法问题:如何在原地且仅使用常量额外内存的情况下,将一组数字重新排列成字典序中下一个更大的排列。文章详细分析了解决方案,并通过示例展示了算法的工作原理。同时,提供了完整的Java代码实现。

464

被折叠的 条评论
为什么被折叠?



