题目描述:
Given n and k, return the k-th permutation sequence.
Notice
n will be between 1 and 9 inclusive.
Example
For n = 3
, all permutations are listed as follows:
"123"
"132"
"213"
"231"
"312"
"321"
If k = 4
, the fourth permutation is "231"
Challenge
题目思路:
O(n*k) in time complexity is easy, can you do it in O(n^2) or less?
这题想法简单,但是parameter太多容易把自己给绕晕@@
想法是这样的,先把1,2,3写到一个sorted array中。对于n = 3, k = 4这个例子来说,首先确定左边第一位的数字:因为(n - 1)位数字的组合一共有2种,所以(k - 1) / 2 = 1得到左边第一位数字为sorted[1] = 2, 而新的k为 k - 2(组合的种类数) * 1 = 2,并且把sorted array在不考虑2的情况下重新排序。这样在剩下的数字1,3中,我们需要找第2(新的k)个permutation,以此类推。
Mycode(AC = 24ms):
class Solution {
public:
/**
* @param n: n
* @param k: the kth permutation
* @return: return the k-th permutation
*/
string getPermutation(int n, int k) {
if (n == 1) return "1";
int total_num = 1, tmp_n = n - 1; // 2
for (int i = 1; i <= n - 1; i++) {
total_num *= i; // 2
}
vector<int> sorted(n, 1);
for (int i = 1; i < n; i++) {
sorted[i] = i + 1;// 1,2,3
}
string ans = "";
int tmp_k = (k - 1) % total_num + 1, // 2
idx = (k - 1) / total_num; // 1
while (tmp_n >= 0) {
ans += to_string(sorted[idx]); //2
sorted[idx] = INT_MAX; // 1,INT_MAX, 3
sort(sorted.begin(), sorted.end()); // 1,3,INT_MAX
total_num = total_num / tmp_n;// 1
tmp_n--;//1
if (tmp_n == 0) {
ans += to_string(sorted[0]);
break;
}
else {
idx = (tmp_k - 1) / total_num; // 0
tmp_k = (tmp_k - 1) % total_num + 1; // 1
}
}
return ans;
}
};