原理参考:
fuxuemingzhu
https://blog.csdn.net/JackZhang_123
c++
// class Solution {
// public:
// string crackSafe(int n, int k) {
// string res = string(n, '0');
// unordered_set<string>s;
// s.insert(res);
// for(int i=0;i<pow(k,n)+11;i++){
// string tmp = res.substr(res.length() - n + 1, n - 1);
// for(int j=0;j<=k-1;j++){
// string key=tmp+to_string(j);
// if(s.find(key)==s.end()) {
// res+=to_string(j);
// s.insert(key);
// break;
// }
// }
// }
// return res;
// }
// };
class Solution {
unordered_set<string>s;
void dfs(string & res,int n,int k){
if(s.size()==pow(k,n)) return;
string tmp = res.substr(res.length() - n + 1, n - 1);
for(int j=k-1;j>=0;j--){
string key=tmp+to_string(j);
if(s.find(key)==s.end()) {
res+=to_string(j);
s.insert(key);
dfs(res,n,k);
}
}
}
public:
string crackSafe(int n, int k) {
string res = string(n, '0');
s.insert(res);
dfs(res,n,k); return res;
}
};
class Solution {
unordered_set<string>s;
bool dfs(string & res,int n,int k){
if(s.size()==pow(k,n)) return true;;
string tmp = res.substr(res.length() - n + 1, n - 1);
for(int j=0;j<k;j++){
string key=tmp+to_string(j);
if(s.find(key)==s.end()) {
res+=to_string(j);
s.insert(key);
if(dfs(res,n,k)) return true;
s.erase(key);
res.erase(res.size()-1,1);
}
}
return false;
}
public:
string crackSafe(int n, int k) {
string res = string(n, '0');
s.insert(res);
if(dfs(res,n,k)) return res;
else return "";
}
};
python
class Solution:
def crackSafe(self, n: int, k: int) -> str:
res=["0"]*n
visited=set()
visited.add("".join(res))
self.dfs(res,visited,n,k)
return "".join(res)
def dfs(self,res,visited,n,k):
if(len(visited)==k**n):
return;
tmp="".join(res[len(res)-n+1:])
for i in range(k-1,-1,-1):
tmp=tmp+str(i)
if tmp not in visited:
res.append(str(i))
visited.add(tmp)
self.dfs(res,visited,n,k)
tmp=tmp[:-1]
利用欧拉回路求解
class Solution {
unordered_set<string>s;
string res="";
void dfs(string & curv,int k){
for(int j=0;j<k;j++){
string key=curv+to_string(j);
if(s.find(key)==s.end()) {
s.insert(key);
string s2=key.substr(1,key.size()-1);
dfs( s2,k);
res+= to_string(j) ;
}
}
// res+=" ";
// res+=curv; 如果这里,则记录的是欧拉回路
}
public:
string crackSafe(int n, int k) {
if(n==1&&k==1 ) return "0";
string start = string(n-1, '0');
// 在初始化时,由于自环的存在,从任一自环开始遍历都可,即n-1 个'0'-'k'
dfs(start,k);
res+=start;
// else return ""
return res;
}
};
class Solution {
unordered_set<string>s;
string res="";
void dfs(string & curv,int k){
for(int j=0;j<k;j++){
string key=curv+to_string(j);
if(s.find(key)==s.end()) {
s.insert(key);
string s2=key.substr(1,key.size()-1);
dfs( s2,k);
res+= to_string(j) ;
}
}
}
public:
string crackSafe(int n, int k) {
if(n==1&&k==1 ) return "0";
if(k==1 ) return string(n,'0');
string start;
// 以任意节点为初始点,而不是以00 为初始点
for(int i=0;i<n-1;i++)
if(i%2==0) start+="1";
else start+="0";
dfs(start,k);
reverse(start.begin(),start.end()); //如果以任意节点为开始,这里必须反转
res+=start;
return res;
}
};