Next Permutation

## Description

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-n，eg：`1,2,3,4`
• 最大排列：n-1，eg：`4,3,2,1`
• `next-permutation`：根据当前排列，生成恰好比它大的下一个排列

## Solution

1. Find the largest index `k` such that `a[k] < a[k + 1]`. If no such index exists, the permutation is the last permutation.
2. Find the largest index `l` greater than `k` such that `a[k] < a[l]`.
3. Swap the value of `a[k]` with that of `a[l]`.
4. Reverse the sequence from `a[k + 1]` up to and including the final element `a[n]`.

1. 查找最大的索引`k`，满足`a[k] < a[k + 1]`。如果不存在则当前已经是最大排列。
2. 查找最大索引`l`，满足`l > k && a[k] < a[l]`
3. 交换`a[k]``a[l]`
4. `a[k + 1], a[k + 2], ..., a[n]`倒序

``````func nextPermutation(nums []int) {
length := len(nums)
if length == 1 {
return
}

k := length - 2
for ; k >= 0; k-- {
if nums[k] < nums[k+1] {
break
}
}

if k == -1 {
// 当前已经是最大排列，则输出最小排列
reverse(nums)
return
}

l := length - 1
for ; l > k; l-- {
if nums[l] > nums[k] {
break
}
}

// 交换 a[k] 和 a[l]
swap(nums, k, l)

// 倒序 a[k]...a[n]
reverse(nums[k+1:])
}

// 交换两个数
func swap(nums []int, i, j int) {
tmp := nums[i]
nums[i] = nums[j]
nums[j] = tmp
}

// 将slice倒序
func reverse(nums []int) {
length := len(nums)
for i := 0; i < length / 2; i++ {
swap(nums, i, length - i - 1)
}
}``````