1.题目描述
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,2
3,2,1
→1,2,3
1,1,5
→1,5,1
实现获取下一个排列的函数,算法需要将给定数字序列重新排列成字典序中下一个更大的排列。
如果不存在下一个更大的排列,则将数字重新排列成最小的排列(即升序排列)。
必须原地修改,只允许使用额外常数空间。
以下是一些例子,输入位于左侧列,其相应输出位于右侧列。
1,2,3
→1,3,2
3,2,1
→1,2,3
1,1,5
→1,5,1
2.相关知识
全排列的生成算法方法是将给定的序列中所有可能的全排列无重复无遗漏地枚举出来。此处全排列的定义是:从n个元素中取出m个元素进行排列,当n=m时这个排列被称为全排列。字典序、邻位对换法、循环左移法、循环右移法、递增进位制法、递减进位制法都是常见的全排列生成算法。
例子:对于元素集合{1,2,3}按字典序生成的全排列是
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
3.Solutions
According to Wikipedia, a man named Narayana Pandita presented the following simple algorithm to solve this problem in the 14th century.
- Find the largest index
k
such thatnums[k] < nums[k + 1]
. If no such index exists, just reversenums
and done. - Find the largest index
l > k
such thatnums[k] < nums[l]
. - Swap
nums[k]
andnums[l]
. - Reverse the sub-array
nums[k + 1:]
.
1 | public static void nextPermutation(int[] nums) { |