版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://cloud.tencent.com/developer/article/1433855
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
class Solution {
public:
string getPermutation(int n, int k) {
string result;
int factorial[n + 1] = {0};
factorial[0] = 1;
for(int i = 1; i <= n; i++) {
factorial[i] = factorial[i - 1] * i;
}
vector<int> nums;
for(int i = 1; i <=n; i++) {
nums.push_back(i);
}
for(int i = n; i > 0; i--) {
int remainder = k % factorial[i - 1];
int quotient = k / factorial[i - 1];
if(remainder) {
quotient++;
}
result += to_string(nums[quotient - 1]);
nums.erase(nums.begin() + quotient - 1);
k %= factorial[i - 1];
if(k == 0) {
k = factorial[i - 1];
}
}
return result;
}
};