Original title address: https://oj.leetcode.com/problems/next-permutation/
Test instructions
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must is in-place, do not allocate extra memory.
Here is some examples. Inputs is in the left-hand column and its corresponding outputs is in the right-hand column.
1,2,3→1,3,2
3,2,1→1,2,3
1,1,5→1,5,1
Problem Solving Ideas:
The next arrangement in the output dictionary order. For example, the full array of 123 builds is: 123,132,213,231,312,321. Then 321 of next permutation is 123. The following algorithm is said to be the classical algorithm in STL. In the current sequence, looking forward from the end to two contiguous ascending elements, the previous mark in the ascending element pair is partition. It then looks for another element greater than partition from the tail and swaps it with the element pointed to by partition, and then sorts the elements after the partition (excluding the elements pointed to by partition). For example 14532, then the ascending pair for 45,partition points to 4, because after partition, except 5 there is no greater than 4 number, so 45 exchange for 54, that is 15432, and then the elements after the partition in reverse order, that is 432 ranked 234, Then the last output of the next permutation is 15234. It's really ingenious.
Code:
classSolution: # @param num, a list of integer # @return a list of integer def nextpermutation (self, num): ifLen (num) <2:returnnum Partition= -1 forIinchRange (len (num)-2, -1, -1): ifNum[i] < Num[i +1]: Partition=I Break ifPartition = =-1:returnnum[::-1] forIinchRange (len (num)-1, Partition,-1): ifNum[i] >Num[partition]: num[i], num[partition]=Num[partition], Num[i] Breaknum[partition+1:] = num[partition +1:][::-1] returnNum
Reference acknowledgements:
The above code is optimized based on [1]
[1] http://www.cnblogs.com/zuoyuan/p/3780167.html
[Leetcode] Next permutation @ Python