-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
105 lines (93 loc) · 2.06 KB
/
main.cpp
File metadata and controls
105 lines (93 loc) · 2.06 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// Source: https://leetcode.com/problems/permutation-sequence
// Title: Permutation Sequence
// Difficulty: Hard
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The set `[1, 2, 3, ...,n]` contains a total of `n!` unique permutations.
//
// By listing and labeling all of the permutations in order, we get the following sequence for `n = 3`:
//
// - `"123"`
// - `"132"`
// - `"213"`
// - `"231"`
// - `"312"`
// - `"321"`
//
// Given `n` and `k`, return the `k^th` permutation sequence.
//
// **Example 1:**
//
// ```
// Input: n = 3, k = 3
// Output: "213"
// ```
//
// **Example 2:**
//
// ```
// Input: n = 4, k = 9
// Output: "2314"
// ```
//
// **Example 3:**
//
// ```
// Input: n = 3, k = 1
// Output: "123"
// ```
//
// **Constraints:**
//
// - `1 <= n <= 9`
// - `1 <= k <= n!`
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <iterator>
#include <list>
#include <numeric>
using namespace std;
class Solution {
public:
string getPermutation(int n, int k) {
auto seq = string(n, '0');
iota(seq.begin(), seq.end(), '1');
for (auto i = 1; i < k; ++i) {
next_permutation(seq.begin(), seq.end());
}
return seq;
}
};
class Solution2 {
constexpr static int factorials[9] = {
1,
1,
1 * 2,
1 * 2 * 3,
1 * 2 * 3 * 4,
1 * 2 * 3 * 4 * 5,
1 * 2 * 3 * 4 * 5 * 6,
1 * 2 * 3 * 4 * 5 * 6 * 7,
1 * 2 * 3 * 4 * 5 * 6 * 7 * 8,
};
public:
string getPermutation(int n, int k) {
// Digit pools
auto digits = list<char>(n);
iota(digits.begin(), digits.end(), '1');
string ans;
--k;
for (auto i = n - 1; i >= 0; --i) {
auto d = k / factorials[i];
k %= factorials[i];
// Pick the d-th largest digit
auto it = digits.begin();
advance(it, d);
// Use the digit
ans += (*it);
digits.erase(it);
}
return ans;
}
};