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 lengththat 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.
Note:
n
will be in the range[1, 4]
.k
will be in the range[1, 10]
.k^n
will be at most4096
.
class Solution {
public:
string crackSafe(int n, int k)
{
string res = "" ;
unordered_set<string> password ;
return res = crackSafe(res , n , k , password) ;
}
string crackSafe(string& s , int n , int k , unordered_set<string> &password)
{
if(s.size() < n)
{
for(int i = 0 ; i < k ; ++i)
{
char c = '0' + i ;
s += c ;
return crackSafe(s , n , k , password) ;
}
}
else if(s.size() == n) password.insert(s) ;
for(int i = 0 ; i < k ; ++i)
{
char c = '0' + i ;
string pw = s.substr(s.size() - n + 1) + c ;
if(!password.count(pw))
{
string res = "" ;
password.insert(pw) ;
s += c ;
res = crackSafe(s , n , k , password);
if( res.size() == pow(k , n) + n - 1) return res ;
else
{
s = s.substr(0 , s.size() - 1) ;
password.erase(pw) ;
}
}
}
return s ;
}
};
class Solution {
public:
string crackSafe(int n, int k)
{
string res = "" ;
unordered_set<string> password ;
return res = crackSafe(res , n , k , password) ;
}
string crackSafe(string& s , int n , int k , unordered_set<string> &password)
{
if(s.size() < n)
{
s += '0' ; // 与上一种不一样的地方,可以发现总有一串最短字符串是以string(n , '0')开头的
return crackSafe(s , n , k , password) ;
}
else if(s.size() == n) password.insert(s) ;
for(int i = 0 ; i < k ; ++i)
{
char c = '0' + i ;
string pw = s.substr(s.size() - n + 1) + c ;
if(!password.count(pw))
{
string res = "" ;
password.insert(pw) ;
s += c ;
res = crackSafe(s , n , k , password);
if( res.size() == pow(k , n) + n - 1) return res ;
else
{
s = s.substr(0 , s.size() - 1) ;
password.erase(pw) ;
}
}
}
return s ;
}
};