Description
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.
Solution
Iteration
很巧妙的找规律题。假设n = 4, k = 15,所有可能的permutation则是:
- 1 + {2, 3, 4};
- 2 + {1, 3, 4};
- 3 + {1, 2, 4};
- 4 + {1, 2, 3};
那么每组的组合数即3! = 6。首先决定第一位,通过15 / 6 = 2,得知第一位应该是3。然后题目变成了在{1, 2, 4}中找到k = 15 - 2 * 6 = 3的permutation。
巧妙之处在于用一个candidates list保存尚未被用过的数字,在每一个迭代中根据计算出的index去在list中进行索引,然后将该数字移出candidates即可。
class Solution {
public String getPermutation(int n, int k) {
int[] factorial = new int[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; ++i) {
factorial[i] = i * factorial[i - 1];
}
List<Integer> candidates = new ArrayList<>();
for (int i = 1; i <= n; ++i) {
candidates.add(i);
}
StringBuilder permutation = new StringBuilder();
--k; // important! Because k starts from 1, not 0
for (int i = 0; i < n; ++i) { // fill ith digit
int index = k / factorial[n - i - 1];
permutation.append(candidates.get(index)); // elegant
candidates.remove(index);
k -= index * factorial[n - i - 1];
}
return permutation.toString();
}
}