753. Cracking the Safe
Input: n = 1, k = 2
Output: "01"
Note: "10" will be accepted too.Input: n = 2, k = 2
Output: "00110"
Note: "01100", "10011", "11001" will be accepted too.// Greedy Method
string crackSafe(int n, int k) { // time: O(k^(n + 1)); space: O(k^n)
string res = string(n, '0'); // start with n 0s
unordered_set<string> visited({res});
for (int i = 0; i < pow(k, n); ++i) {
string pre = res.substr(res.size() - (n - 1), n - 1);
for (int j = k - 1; j >= 0; --j) {
string cur = pre + to_string(j);
if (!visited.count(cur)) {
visited.insert(cur);
res += to_string(j);
break;
}
}
}
return res;
}Last updated