题目
The set [1,2,3,…,n] contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
分析
我的思路很奇怪
用递归。
- 先判断第k个排序会影响到哪一位
- 得到三个值,分别代表变动的数字个数,前一位增长值和下一次递归的k
class Solution {
public static String getPermutation(int n, int k) {
k = k-1;
int [] cons = new int[11];
cons[0] = 1;
cons[1] = 1;
for (int i = 2; i<=10; i++) {
cons[i] = i*cons[i-1];
}
int[] array = new int[n];
for (int i =0; i<n; i++) {
array[i] = i+1;
}
StringBuffer ret = new StringBuffer("");
getkIndex(ret, array, k, cons);
return ret.toString();
}
public static void getkIndex(StringBuffer xx, int[] array, int k, int[] cons) {
Arrays.sort(array);
int length = array.length;
if (length ==1) {
xx.append(array[0]);
return;
} else if (length == 0) {
return;
}
int variNum = 0;
int nextK = 0;
int increase = 0;
for (int i =0; i<length; i++) {
if (k<cons[i+1]) {
variNum = i;
nextK = k%cons[i];
increase = k/cons[i];
break;
}
}
int tmp = array[length-variNum-1];
array[length-variNum-1] = array[length-variNum-1+increase];
array[length-variNum-1+increase] = tmp;
for (int i = 0; i< length-variNum; i++) {
xx.append(array[i]);
}
int[] nestArray = new int[variNum];
System.arraycopy(array, length-variNum, nestArray, 0, variNum);
getkIndex(xx, nestArray, nextK, cons);
}
}