Cracking the Safe

There is a box protected by a password. The password is a sequence of n digits where each digit can be one of the first k digits 0, 1, ..., k-1.

While entering a password, the last n digits entered will automatically be matched against the correct password.

For example, assuming the correct password is "345", if you type "012345", the box will open because the correct password matches the suffix of the entered password.

Return any password of minimum length that is guaranteed to open the box at some point of entering it.

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.

思路:要想length最短,就是前一个密码n - 1位,跟后面的重复;like:123, 234  - 》 1234

密码总共有k ^n 个,长度为k ^n + n - 1个;Time: O (K^N) Space:O(K^N)

class Solution {
    public String crackSafe(int n, int k) {
        long total = (long) Math.pow(k, n);
        HashSet<String> visited = new HashSet<String>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++) {
            sb.append("0");
        }
        visited.add(sb.toString());
        dfs(sb, n, k, visited, total);
        return sb.toString();
    }
    
    private boolean dfs(StringBuilder sb, int n, int k, 
                        HashSet<String> visited, long total) {
        if(visited.size() == total) {
            return true;
        }
        for(int i = 0; i < k; i++) {
            sb.append(i);
            String password = sb.substring(sb.length() - n, sb.length());
            if(!visited.contains(password)) {
                visited.add(password);
                if(dfs(sb, n, k, visited, total)) {
                    return true;
                }
                visited.remove(password);
            }
            sb.deleteCharAt(sb.length() - 1);
        }
        return false;
    }
}
发布了710 篇原创文章 · 获赞 13 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/u013325815/article/details/105403822