# [LeetCode] 756. Pyramid Transition Matrix

## 题目描述

We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like 'Z'.

For every block of color C we place not in the bottom row, we are placing it on top of a left block of color A and right block of color B. We are allowed to place the block there only if (A, B, C) is an allowed triple.

We start with a bottom row of bottom, represented as a single string. We also start with a list of allowed triples allowed. Each allowed triple is represented as a string of length 3.

Return true if we can build the pyramid all the way to the top, otherwise false.

Example 1:

Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]
Output: true
Explanation:
We can stack the pyramid like this:
A
/ \
D   E
/ \ / \
X   Y   Z

This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples.

Example 2:

Input: bottom = "XXYX", allowed = ["XXX", "XXY", "XYX", "XYY", "YXZ"]
Output: false
Explanation:
We can't stack the pyramid to the top.
Note that there could be allowed triples (A, B, C) and (A, B, D) with C != D.

Note:
bottom will be a string with length in range [2, 8].
allowed will have length in range [0, 200].
Letters in all strings will be chosen from the set {‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’, ‘G’}.

## C++ 实现

class Solution {
public:
bool pyramidTransition(string bottom, vector<string>& allowed) {
// 构建allowed_map, hash_map 的key是小金子塔的底部，value 是所有允许的顶部的集合
for (const string& str : allowed)
{
const string& key = str.substr(0, 2);
const char value = str.back();
if (allowed_map.count(key))
{
allowed_map[key].insert(value);
}
else
{
allowed_map[key] = {value};
}
}
// 递归搜索
return dfs(bottom);
}
private:
unordered_map<string, set<char>> allowed_map;

bool dfs(const string& bottom)
{
// 终止条件
if (bottom.size() == 1) return true;
// 首先判断上一层无法构建的情况，如果无法构建直接return false
for(size_t i = 0; i < bottom.size() - 1; i++)
{
if (!allowed_map.count(bottom.substr(i, 2)))
{
return false;
}
}
vector<string> candidates;
candidates.reserve(bottom.size() - 1);
string path;
//使用dfs的方式找到上一层所有可能结果
getCandidates(bottom, 0, path, candidates);
//遍历所有结果进行递归搜索
for(const string& candidate : candidates)
{
if (dfs(candidate))
{
return true;
}
}
return false;
}
// dfs的方式找到所有可能的上一层的结果
// 结果存储到 candidates 数组中
// cur 存储当前dfs的进度
void getCandidates(const string& bottom,
size_t idx,
string& cur,
vector<string>& candidates)
{
if (idx == bottom.size() - 1)
{
candidates.push_back(cur);
return;
}

for(const char c : allowed_map.at(bottom.substr(idx, 2)))
{
cur += c;
getCandidates(bottom, idx + 1, cur, candidates);
cur.pop_back();
}
}
};
• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

carbon06

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-26
03-18 442

11-28 543
07-22 96
09-19 298
01-28 169
02-23 67
10-24 1万+