-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutation_sequence.cpp
69 lines (62 loc) · 1.48 KB
/
permutation_sequence.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
* =====================================================================================
*
* Filename: permutation_sequence.cpp
*
* Description: 60. Permutation Sequence.
*
* Version: 1.0
* Created: 04/03/19 07:36:31
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
class Solution
{
public:
std::string getPermutation(int n, int k)
{
std::vector<int> digits;
for (int i = 1; i <= n; i++)
{
digits.push_back(i);
}
std::vector<int> factorials(n + 1);
factorials[0] = 1;
for (int i = 1; i <= n; i++)
{
factorials[i] = factorials[i - 1] * i;
}
std::string perm;
k--;
for (int i = 1; i <= n; i++)
{
int idx = k / factorials[n - i];
perm += (char)(digits[idx] + '0');
digits.erase(digits.begin() + idx);
k %= factorials[n - i];
}
return perm;
}
};
int main(int argc, char* argv[])
{
int n = 3;
int k = 3;
if (argc == 3)
{
n = atoi(argv[1]);
k = atoi(argv[2]);
}
auto perm = Solution().getPermutation(n, k);
printf("The permutation is: %s\n", perm.c_str());
return 0;
}