forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cracking-the-safe.cpp
80 lines (76 loc) · 2.25 KB
/
cracking-the-safe.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
70
71
72
73
74
75
76
77
78
79
80
// Time: O(k^n)
// Space: O(k^n)
// https://en.wikipedia.org/wiki/De_Bruijn_sequence
// https://en.wikipedia.org/wiki/Lyndon_word
class Solution {
public:
string crackSafe(int n, int k) {
const int M = pow(k, n - 1);
vector<int> P;
for (int i = 0; i < k; ++i) {
for (int q = 0; q < M; ++q) {
P.emplace_back(q * k + i); // rotate: i*k^(n-1) + q => q*k + i
}
}
const int total = pow(k, n);
string result(n - 1, '0' + k - 1);
for (int i = 0; i < total; ++i) {
int j = i;
// concatenation in lexicographic order of Lyndon words
while (P[j] >= 0) {
result.push_back('0' + j / M);
auto Pj = P[j];
P[j] = -1;
j = Pj;
}
}
return result;
}
};
// Time: O(n * k^n)
// Space: O(n * k^n)
class Solution2 {
public:
string crackSafe(int n, int k) {
string result(n, '0' + k - 1);
unordered_set<string> lookup;
lookup.emplace(result);
const int total = pow(k, n);
while (lookup.size() < total) {
const auto& node = result.substr(result.length() - n + 1);
for (int i = 0; i < k; ++i) {
const auto& neighbor = node + to_string(i);
if (!lookup.count(neighbor)) {
lookup.emplace(neighbor);
result.push_back('0' + i);
break;
}
}
}
return result;
}
};
// Time: O(n * k^n)
// Space: O(n * k^n)
class Solution3 {
public:
string crackSafe(int n, int k) {
unordered_set<string> lookup;
string result(n - 1, '0' + k - 1);
auto node = result;
dfs(k, node, &lookup, &result);
return result;
}
private:
void dfs(int k, const string& node, unordered_set<string> *lookup, string *result) {
for (int i = 0; i < k; ++i) {
const auto& neighbor = node + to_string(i);
if (!lookup->count(neighbor)) {
lookup->emplace(neighbor);
result->push_back('0' + i);
dfs(k, neighbor.substr(1), lookup, result);
break;
}
}
}
};