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:
n
will be in the range[1, 4]
.k
will be in the range[1, 10]
.k^n
will be at most4096
.
Solution
(1) Java
class Solution {
public String crackSafe(int n, int k) {
if (n == 0 || k == 0) {
return "";
}
if (n == 1 && k == 1) {
return "0";
}
char[] chars = new char[n];
Arrays.fill(chars, '0');
String passwd = new String(chars);
Set<String> cache = new HashSet<>();
cache.add(passwd);
return dfs(passwd, cache, n, k, (int)Math.pow(k, n));
}
private String dfs(String passwd, Set<String> cache, int n, int k, int total) {
if (cache.size() == total) {
return passwd;
}
for (int i = 0; i < k; i++) {
String npasswd = passwd.substring(passwd.length()-n+1)+i;
if (!cache.contains(npasswd)) {
cache.add(npasswd);
String rst = dfs(passwd+i, cache, n, k, total);
if (rst.length() > 0) {
return rst;
} else {
cache.remove(npasswd);
}
}
}
return "";
}
}
(2) Python
(3) Scala