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
寻找数组字典序的下一个。如果把这个数组看成一个integer就是找出仅比他大的那个数。
i从倒数第二位开始往前扫,j从最后一位往前扫到i,找到i比j小的那个数。两者互换再把i位置后面的数从小到大排序。保证了这个数比给定的数大的最少。如果j扫到0了证明数组是逆序排序的 颠倒一下即可。