代码拉取完成,页面将自动刷新
// Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed,
// b is the length of bottom
// Space: O((a^(b+1)-a)/(a-1)) = O(a^b)
// dfs solution
class Solution {
public:
bool pyramidTransition(string bottom, vector<string>& allowed) {
vector<vector<vector<int>>> edges(7, vector<vector<int>>(7));
unordered_set<string> lookup;
for (const auto& s: allowed) {
edges[s[0] - 'A'][s[1] - 'A'].emplace_back(s[2] - 'A');
}
return pyramidTransitionHelper(bottom, edges, &lookup);
}
private:
bool pyramidTransitionHelper(const string& bottom, const vector<vector<vector<int>>>& edges,
unordered_set<string> *lookup) {
if (bottom.size() == 1) {
return true;
}
for (int i = 0; i < bottom.size() - 1; ++i) {
if (edges[bottom[i] - 'A'][bottom[i + 1] - 'A'].empty()) {
return false;
}
}
if (lookup->count(bottom)) {
return false;
}
lookup->emplace(bottom);
string new_bottom(bottom.size() - 1, 'A');
return dfs(bottom, edges, &new_bottom, 0, lookup);
}
bool dfs(const string& bottom, const vector<vector<vector<int>>>& edges, string *new_bottom, int idx,
unordered_set<string> *lookup) {
if (idx == bottom.size() - 1) {
return pyramidTransitionHelper(*new_bottom, edges, lookup);
}
for (const auto& i : edges[bottom[idx] - 'A'][bottom[idx + 1] - 'A']) {
(*new_bottom)[idx] = i + 'A';
if (dfs(bottom, edges, new_bottom, idx + 1, lookup)) {
return true;
}
}
return false;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。