-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutation Sequence.cpp
More file actions
50 lines (47 loc) · 1.29 KB
/
Permutation Sequence.cpp
File metadata and controls
50 lines (47 loc) · 1.29 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
// Time: O((n-1)!), fast enough to get accepted, but not even enough to hit the best solution.
class Solution {
public:
string getPermutation(int n, int k) {
if (n == 1) return "1";
int f = factorial(n - 1);
int pfx = k / f, sno = k % f;
if (sno == 0) {-- pfx; sno = f;}
string s(n, '0');
for (int i = 0; i < n; ++i) s[i] += i + 1;
swap(s[pfx], s[0]);
sort(s.begin() + 1, s.end());
while (-- sno > 0) next_permutation(s.begin(), s.end());
return s;
}
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
};
// Time: O(n^2), as there is an erase process at cost of O(n) time during each iteration of the outter loop at cost of O(n) time.
// ...
class Solution {
public:
string getPermutation(int n, int k) {
if (n == 1) return "1";
int f = 1;
string a(n, '0');
for (int i = 0; i < n; ++i) {
a[i] += i + 1;
f *= i + 1;
}
string s(n, '0');
int i = 0;
while (n) {
f /= n;
int pfx = k / f;
k %= f;
if (k == 0) {-- pfx; k = f;}
s[i++] = a[pfx];
a.erase(pfx, 1);
-- n;
}
return s;
}
};
//