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"
Example 2:
Input: n = 4, k = 9 Output: "2314"
解法:按照k的位置一步步缩小处理范围,可以使用迭代也可以使用递归。这里使用了迭代的方法。
举个例子:比如说输入是4,9.
先看第一位要取什么,知道k=9,那我把 4!/4 知道每个槽位放六个数,故第一位必然是“2”。以此类推就行。
本题我觉得难点是在于list的操作,需要一个数据结构保存1到n,取出相应数字之后还能有序。这里使用了ArrayList。
还有一个位数ins时,需要用(k-1)/cnt,这里需要认真理解下,因为槽位内也是从0开始index,所有需要减一。
class Solution {
public String getPermutation(int n, int k) {
int cnt = 1;//阶乘的结果
List<Integer> ts = new ArrayList<Integer>();//数字集,自动排序
for(int i=1;i<=n;i++){
cnt = cnt * i;
ts.add(i);
}
//判断k是否大于阶乘/n,缩减范围
//需要一个数据结构保存1到n,并且支持取出相应的数字之后还能有序
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;i++){
cnt = cnt/(n-i);
if(k>=0){ //0也是index
int ins = (k-1)/cnt; //why?类比为一个槽位内也是index从0开始的
k = k-ins*cnt;
sb.append(ts.get(ins));
ts.remove(ts.get(ins));
}
}
return sb.toString();
}
}