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