blob: f0903551aafa2d8d017892e125043913df143457 (
plain)
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#include <string>
#include <vector>
using std::string;
class Solution
{
public:
string getPermutation(int n, int k)
{
k--;
string result;
result.reserve(n);
std::vector<char> nums;
nums.reserve(n);
for (int i = 1; i <= n; i++)
{
nums.push_back(i + '0');
}
n--;
int fac = 1;
for (int i = 2; i <= n; i++)
{
fac *= i;
}
while (n > 0)
{
const int index = k / fac;
k = k % fac;
result += nums[index];
nums.erase(nums.cbegin() + index);
fac /= n--;
}
result += nums.front();
return result;
}
};
|