753. Craking 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.Last updated
Was this helpful?
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.Last updated
Was this helpful?
Was this helpful?
class Solution {
public String crackSafe(int n, int k) {
String start = String.join("", Collections.nCopies(n, "0"));
StringBuilder sb = new StringBuilder(start);
Set<String> visited = new HashSet<>();
visited.add(start);
int target = (int) Math.pow(k,n);
DFS(sb, visited, target, n, k);
return sb.toString();
}
private boolean DFS(StringBuilder sb, Set<String> visited, int target, int n, int k){
// base case: all n-length combinations among digits 0 ~ (k -1)
if(visited.size() == target)
return true;
String last = sb.substring(sb.length() - ( n - 1));
/* DFS expansion*/
for (char ch = '0'; ch < '0' + k; ch ++){
String cand = last + ch;
if(!visited.contains(cand)){
visited.add(cand);
sb.append(ch);
if(DFS(sb, visited, target, n, k))
return true;
visited.remove(cand);
sb.deleteCharAt(sb.length() - 1);
}
}
return false;
}
}class Solution {
public:
string crackSafe(int n, int k) {
string ans = string(n, '0');
unordered_set<string> visited;
visited.insert(ans);
for(int i = 0; i < pow(k,n);i++){
string prev = ans.substr(ans.size()-n+1,n-1);
for(int j = k - 1; j >= 0; j--){
string now = prev + to_string(j);
if(!visited.count(now)){
visited.insert(now);
ans += to_string(j);
break;
}
}
}
return ans;
}
};