leetcode 753. Cracking the Safe

753Cracking 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:

  1. n will be in the range [1, 4].
  2. k will be in the range [1, 10].
  3. k^n will be at most 4096.


题目:找到一个密码字符串可以以每一位作为开头测试。


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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值