package com.ytx.array;
/**
* 题目 : next-permutation
*
* 描述: 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
* @author yuantian xin
*
* 题意就是说按照字典序(升序)生成当前排列的下一个排列,如果输入序列已经是降序排列,说明这个是最后一个排列,直接反序输出即可。
* 1234->1243->1324->1342->1423->1432->4123->...->4321->1234;
*
*/
public class Next_permutation {
public void nextPermutation(int[] num) {
int len = num.length;
//从后往前找到第一个升序位置
int pos = -1;
for(int i = len - 1; i > 0; i--) {
if(num[i] > num[i-1]) {
pos = i - 1;
break;
}
}
//如果不存在升序,说明这个序列是最后一个排列,直接逆序这个序列并return。
if(pos < 0) {
reverse(num, 0, len-1);
return;
}
//如果找到了升序位置,那么从后往前找,找到pos之后第一个比num[pos]大的位置,并且交换这两个位置上的数。
for(int i = len-1; i > pos; i--) {
if(num[i] > num[pos]) {
int temp = num[i];
num[i] = num[pos];
num[pos] = temp;
break;
}
}
//逆序pos位置之后的数字
reverse(num, pos + 1, len-1);
}
public void reverse(int[] num, int begin, int end) {
int temp;
while(begin < end) {
temp = num[begin];
num[begin] = num[end];
num[end] = temp;
begin++;
end--;
}
}
public static void main(String[] args) {
/*int [] num = {1,2,3,6,5,4};*/
int [] num = {1,2,3,4,6,5};
new Next_permutation().nextPermutation(num);
for(int i = 0; i < num.length; i++) {
System.out.print(num[i] + " ");
}
}
}