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
public class Solution {
public void nextPermutation(int[] num) {
boolean isDone = false;
int[] nearest = new int[2];//nearest[0] for value, nearest[1] for index
if(num.length != 1){
//find inverted sequence
for(int i=num.length-2;i >= 0;i--){
//number 10 is never acheved by subtraction between 2 numbers
nearest[0] = Integer.MAX_VALUE;
nearest[1] = -1;
for(int j = i+1;j < num.length ;j++){
if(num[i] < num[j] && nearest[0] > (num[j] - num[i])){
//find number nearest num[i]
nearest[0] = num[j] - num[i];
nearest[1] = j;
}
}
if(nearest[0] != Integer.MAX_VALUE){
//swap
int tmp = num[i];
num[i] = num[nearest[1]];
num[nearest[1]] = tmp;
//sort i+1 to num.length - 1
Arrays.sort(num, i+1, num.length);
isDone = true;
break;
}
}
int tmp;
//if there is no inverted sequence,invert all of it
if(isDone == false)
for(int i=0;i < num.length / 2;i++){
tmp = num[i];
num[i] = num[num.length - 1 - i];
num[num.length - 1 - i] = tmp;
}
}
}
}
原理:外层递减扫描从num[]的倒数第2位开始,假设当前扫描位为x,开始查找所有逆序(x, y),将x与y(y满足min(y-x))交换,然后将x(不包括x)以后的序列按升序排列。