给定 n 和 k,求n的全排列中字典序第k个排列.
样例
样例 1:
输入: n = 3, k = 4
输出: "231"
解释:
n = 3时, 全排列如下:
"123", "132", "213", "231", "312", "321"
样例 2:
输入: n = 1, k = 1
输出: "1"
挑战
O(n*k)很容易, 你可以做到O(n^2n
2
)或更低的时间复杂度吗?
注意事项
1 ≤ n ≤ 9
class Solution {
public:
/**
* @param n: n
* @param k: the k th permutation
* @return: return the k-th permutation
*/
string getPermutation(int n, int k) {
// write your code here
string start="123456789";
string res="";
vector<int> factor(n,1);
for (int i = 1; i < n; i++) {
factor[i]=factor[i-1]*i;
}
k--;
for (int i = n; i >= 1 ; i--) {
int index=k/factor[i-1];
k%=factor[i-1];
res.push_back(start[index]);
start.erase(index,1);
}
return res;
}
};