Test instructions
Find the next dictionary order
Example 1
Input:123
Generated:123,213,231,312,321
Result: one of the 123 is the next
Example 2
Input:321
Generated:123,213,231,312,321
Result: where 123 is the next 321 ( loop )
Ideas
Any arrangement:a[0],a[1]... A[n]
Find i, meet A[i]<a[i+1], and have a[i+1]>=a[i+2]... >=a[n]
From A[i+1] to a[n] , select the first number smaller than a[i] a[k]
a[i+1 ] to A[n] reverse position after swapping A[i] with A[k]
Then a[0],a[1]... A[n] in the next row column
A[0],a[1]... A[k]a[n]a[n-1]... A[k+1]a[i]a[k-1]a[i+1]
??
Example
Arranged as:236541
Steps
1, from the forward look, to find the first is not in order to increase the number, such as the example of 3, before the 1456 are in turn, note the position p, at this time p=1
2. Discussion of the situation
a, if all are growth in turn, then the arrangement is the last arrangement, the next is the first, as long as the arrangement in reverse order, such as 654321 Next is 123456
b, if p exists, look backward from p , find the first number smaller than him, this example is 1, then the pointer moves back to the number of the previous number, this example is 4, Exchange 3 and 4 of the position, this time for 246531
3, finally the number after the p reverse, that is, 6531 reverse order, get the next sequence 241356
"Leetcode" Next permutation