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.
給定一個數字n,求從1到n的第k個排列。
這道題可以用深度優先搜索,配合一個全局計數變量解決,但是當k較大時,時間復雜度會趨近于n的階乘。
觀察給出的例子,第一位數子每兩種組合加1,如果是四個數組,就是每6種組合加1,第i位的變化頻次和它后面數組的組合數有關,所以k除以組合數 就可以求出第一位的數字。從數字list中刪除這個數字,更新k值,可以按此方法求后面的數字。
public String getPermutation(int n, int k) {
if (k <= 0 || n <= 0) {
return "";
}
StringBuilder buffer = new StringBuilder();
//n個數字的排列數
int[] cnts = new int[n + 1];
cnts[0] = 1;
for (int i = 1; i <= n; i++) {
cnts[i] = cnts[i-1] * i;
}
List<Integer> nums = new ArrayList<>();
for (int i = 1; i <= n; i++) {
nums.add(i);
}
k--;
while (nums.size() > 0) {
int index = k / cnts[n - 1];
buffer.append(nums.get(index));
k -= index * cnts[n - 1];
nums.remove(index);
}
return buffer.toString();
}