题目链接:传送门
代码:
class Solution {
public:
unordered_map<string, vector<char>> mp;
unordered_map<string, int>mp_s;
char word[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
string res[10];
bool solve(int p, int h) {
if(mp_s[res[h]] == -1)return false;
if(h > 0 && res[h].size() == res[h - 1].size() - 1) {
bool rt = 0;
if(res[h].size() == 1) {
rt = true;
}
else {
rt = solve(1, h + 1);
}
if(!rt)mp_s[res[h]] = -1;
return rt;
}
for(int i = p; i < res[h - 1].size(); i++) {
string tmp = res[h - 1].substr(i - 1, 2);
for(int j = 0; j < mp[tmp].size(); j++) {
res[h] += mp[tmp][j];
if(solve(i + 1, h)) {
return true;
}
res[h].pop_back();
}
}
return false;
}
bool pyramidTransition(string bot, vector<string>& ald) {
for(int i = 0;i < ald.size(); i++) {
mp[ald[i].substr(0, 2)].push_back(ald[i][2]);
}
res[0] = bot;
return solve(1, 1);
}
};
python:
class Solution:
def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
mp = defaultdict(list)
for t in allowed:
mp[t[:2]].append(t[2])
@cache
def dfs(s):
p = []
if len(s) == 1:
return True
for i in range(1, len(s)):
cur = mp[s[i -1:i + 1]]
if len(cur) == 0:
return False
p.append(cur)
for ns in product(*p):
if dfs("".join(ns)):
return True
return False
return dfs(bottom)