Leetcode | 754. Cracking the Safe 数学原理题

Thereis 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.

Youcan keep inputting the password, the password will automatically be matchedagainst the last n digitsentered.

Forexample, assuming the password is "345", I can open it when I type "012345", but I enter a total of 6 digits.

Pleasereturn any string of minimum length that is guaranteed to open the box afterthe entire string is inputted.

Example1:

Input: n = 1, k = 2

Output: "01"

Note: "10" will be accepted too.

Example2:

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.

这题要你求出最短的包含所有长度为n的密码的一个字符串组合,这里需要注意的是密码组合里面的任何一个字符都是从0-n这个范围取,这一题好像有一个定理,就是对于长度为n的字符组合,每一个字符都是从a1,a2,a3…ak里面取得,好像一定存在一个a1,a2,…an开头,长度为n^k+n-1的字符组合,能够包含所有的长度为n得密码每一个字符都是从a1,a2,a3,a4,a5..ak里面取的所有密码组合

通过这一题我还学会了string的push_back和pop_back的方法,vector向量数组也有这两个方法

class Solution {

public:

   #define FOR(i,s,e) for(int i=s;i<=e;i++)

set<string> dead;

string e;

bool dp(int up,int t,string s,int k)

{

      string tmp = s.substr(1);

      FOR(i, 0, k - 1)

      {

            tmp.push_back((char)(i+'0'));

            if (dead.count(tmp))

            {

                  tmp.pop_back();

                  continue;

            }

            dead.insert(tmp);

            e.push_back((char)(i + '0'));

            if (t == up) { return true; }

            if (dp(up, t + 1, tmp, k)) returntrue;

            e.pop_back();

            dead.erase(tmp);

            tmp.pop_back();

      }

      return false;

}

stringcrackSafe(int n, int k) {

      string s = "";

     

      int theEnd=1;

      FOR(i, 1, n)

      {

            theEnd *= k;

            s = s + '0';

            e += '0';

      }

      dead.insert(s);

      dp(theEnd - 1, 1, s,k);

     

      return e;

}

};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值