-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrackingtheSafe.cpp
More file actions
33 lines (30 loc) · 812 Bytes
/
crackingtheSafe.cpp
File metadata and controls
33 lines (30 loc) · 812 Bytes
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
// Source: https://leetcode.com/problems/cracking-the-safe/
// Author: Miao Zhang
// Date: 2021-03-07
class Solution {
public:
string crackSafe(int n, int k) {
if (n == 1 && k == 1) return "0";
visited = unordered_set<string>();
string start;
for (int i = 0; i < n - 1; i++) {
start.push_back('0');
}
dfs(start, k);
res += start;
return res;
}
private:
unordered_set<string> visited;
string res;
void dfs(string node, int k) {
for (int edge = 0; edge < k; edge++) {
string val = node + to_string(edge);
if (!visited.count(val)) {
visited.insert(val);
dfs(val.substr(1), k);
res += to_string(edge);
}
}
}
};