Cracking the Safe

本文介绍了一种用于解锁密码箱的算法,该算法确保通过输入特定序列的数字组合,能够覆盖所有可能的密码组合,从而在某一点上必定能打开密码箱。文章详细解释了算法的原理,包括如何构造最短的有效密码序列,以及其实现过程中的时间和空间复杂度。
摘要由CSDN通过智能技术生成

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;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值