Leetcode 60. Permutation Sequence

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Permutation Sequence

2. Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
}
};

Reference

  1. https://leetcode.com/problems/permutation-sequence/description/
如果有收获,可以请我喝杯咖啡!