Topic
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
Resolution
is actually the displacement generation algorithm Dictionary ordering method to generate the next arrangement of the current arrangement.
Previously written full permutation algorithm "Leetcode" Permutations Problem solving report
The difference is that the whole arrangement above is generated from small to large, and there is no 2nd step in the code.
public class Solution {public void nextpermutation (int[] num) {//1. Find last ascending position pos int pos =-1; for (int i = num.length-1; i > 0; i--) {if (Num[i] > Num[i-1]) {pos = i-1; Break }}//2. If there is no ascending order, that is, this number is the largest, then the array is inverted if (pos < 0) {reverse (num, 0, num.length-1 ); Return }//3. There is an ascending order, then the last position that is larger than the POS is found for (int i = num.length-1; i > pos; i--) {if (Num[i] > Num[pos]) {int tmp = Num[i]; Num[i] = Num[pos]; Num[pos] = tmp; Break }}//4. number reverse (num, pos + 1, num.length-1) after the reverse POS; public void reverse (int[] num, int begin, int end) {int L = begin, R = end; while (L < r) {int tmp = num[l]; NUM[L] = Num[r]; NUM[R] = tmp; l++; r--; } }}
"Leetcode" Next permutation problem solving report