题目描述
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:1
2
3
4
5
6
7
8
9
10
11Input: 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:1
2
3
4
5Input: 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’}.
输入是一个叫bottom 的字符串以及allowed 数组,bottom 字符串代表金字塔的最底层,allowed 数组给出了所有可能的金字塔的构建方法。给定这两个数组后判断是否能建成金字塔。
解题思路是使用递归的方式,每次递归构建出上一层,递归的终止条件是当前层只有一个字符。
需要注意的是,每次递归时需要使用dfs 搜索找出当前层所有可能的构造方式。具体见实现以及注释。
C++ 实现
1 | class Solution { |