Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
pyramid-transition-matrix.cpp 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-01-01 21:42 +08:00 . Update pyramid-transition-matrix.cpp
// 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;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助