753. Cracking the Safe
There is a box protected by a password. The password is n digits, where each letter can be one of the first k digits 0, 1, ..., k-1.
You can keep inputting the password, the password will automatically be matched against the last n digits entered.
For example, assuming the password is "345", I can open it when I type "012345", but I enter a total of 6 digits.
Please return any string of minimum length that is guaranteed to open the box after the entire string is inputted.
Example 1:
Input: n = 1, k = 2 Output: "01" Note: "10" will be accepted too.
Example 2:
Input: n = 2, k = 2 Output: "00110" Note: "01100", "10011", "11001" will be accepted too.
Note:
nwill be in the range[1, 4].kwill be in the range[1, 10].k^nwill be at most4096.
1、使用DFS,找一条路可以走到底的。
2、密码字符串的长度是一定的。DFS结束条件就是看字符串长度。
3、最重要就是要知道这个目标字符串的长度是 n + k^n - 1
class Solution {
public:
string crackSafe(int n, int k)
{
int sSize = n + pow(k, n) - 1;
ret = "";
for (int i = 0; i < n; i++)
ret += "0";
st.insert(ret);
DFS(ret, n, k, sSize);
return ret;
}
private:
string ret;
set<string> st;
int DFS(string s, int n, int k, int sSize) //4 2 举例
{
if (s.size() == sSize) //找到了正确答案
{
ret = s;
return -1; //返回-1代表不用往下找了
}
string tmp = s.substr(s.size() - n + 1); //截取后面的3位
for (int i = 0; i < k; i++)
{
string new_s = tmp + to_string(i);
if (st.find(new_s) == st.end())
{
st.insert(new_s);
if ( DFS(s + to_string(i), n, k, sSize) == -1) //已经找到了
return -1;
st.erase(new_s);
}
}
return 0;
}
};
本文介绍了一种破解固定长度且由特定数字组成的保险箱密码的方法。通过深度优先搜索(DFS)策略,构造出一种能确保在输入完整字符串后必定打开保险箱的最短密码串。文章详细解释了算法实现细节,并提供了代码示例。
446

被折叠的 条评论
为什么被折叠?



