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 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.
Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: “213”
给出数字n和k,找出n!的排列组合中第k个排列组合
思路:
可以看到固定首位数字后,还剩下(n-1)个数,也就是说以每个数字开头的排列组合有(n-1)! 个,只需用(k-1)/(n-1)!+1就能确定首位数字,
确定首位数字后,用k % (n-1)! 得到子序列中index的k,
然后每个首位数字对应(n-2)!个组合,用(k-1)/(n-2)!+1确定第二位数字,
这样循环下去,
一共n个数字,首位对应后面的(n-1)!个组合,最后一位对应最后0!个组合,所以循环从(n-1)到0
而且可以看到比如“213”,确认首位2之后,下面要取“13”,“31”两个组合中的一个,比如确认是这个子序列中的第2个(k=2),这时首位数字要取3而不是2,所以可以看出每确定完一个数字,要把该数字从数字表中删除,避免重复利用
public String getPermutation(int n, int k) {
String result = "";
int[] sum = new int[n];
ArrayList<Integer> index = new ArrayList<>();
Arrays.fill(sum, 1);
index.add(1);
for(int i = 1; i < n; i++) {
sum[i] = sum[i-1] * i;
index.add(i);
}
index.add(n);
k --;
for (int i = n-1; i >= 0; i--) {
int num = k / sum[i] + 1;
result += index.get(num);
index.remove(num);
k = k % sum[i];
}
return result;
}