753. Cracking the Safe
https://leetcode.com/problems/cracking-the-safe/description/
/*
* @lc app=leetcode id=753 lang=cpp
*
* [753] Cracking the Safe
*/
class Solution {
public:
bool dfs(string &res, const int n, const int k, unordered_set<string> &path) {
if (path.size() == pow(k, n)) return true;
string cur = res.substr(res.length() - n + 1, n - 1);
for (char c = '0'; c < '0' + k; ++c) {
cur.push_back(c);
if (!path.count(cur)) {
res.push_back(c);
path.insert(cur);
if (dfs(res, n, k, path)) return true;
path.erase(cur);
res.pop_back();
}
}
return false;
}
string crackSafe(int n, int k) {
string res(n, '0');
unordered_set<string> path{res};
dfs(res, n, k, path);
return res;
}
};
Previous1284. Minimum Number of Flips to Convert Binary Matrix to Zero MatrixNext1706. Where Will the Ball Fall
Last updated