31. Next Permutation
Difficulty: Medium
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,23,2,1 → 1,2,31,1,5 → 1,5,1
求下一个字典序
Solution
只要有顺序的,就有下一个比它大的字典序
因此第一步找出最后一个顺序的位置j,然后找到它后面,最后一个比它大的位置k
// 如果从后开始找,j是第一个降序的位置,k是第一个比它大的位置。
交换 j k
再把j+1到最后逆序。
1 | class Solution { |
1 | class Solution { |