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. Input: bottom = "XYZ", allowed = ["XYD", "YZE", "DEA", "FFF"]
  2. Output: true
  3. Explanation:
  4. We can stack the pyramid like this:
  5. A
  6. / \
  7. D E
  8. / \ / \
  9. X Y Z
  10.  
  11. This works because ('X', 'Y', 'D'), ('Y', 'Z', 'E'), and ('D', 'E', 'A') are allowed triples.

Example 2:

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

Note:

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

这道题让我们累一个金字塔,用字母来代表每块砖的颜色,给了一个allowed数组,里面都是长度为三的字符串,比如“ABC”表示C可以放在A和B的上方,注意AB上面也可以放其他的,比如“ABD”也可以同时出现,不过搭积木的时候只能选择一种。给了我们一个bottom字符串,是金字塔的底层,问我们能不能搭出一个完整的金字塔。那么实际上我们就是从底层开始,一层一层的向上来累加,直到搭出整个金字塔。我们先来看递归的解法,首先由于我们想快速知道两个字母上方可以放的字母,需要建立基座字符串和上方字符集合之间的映射,由于上方字符可以不唯一,所以用个HashSet来放字符。我们的递归函数有三个参数,当前层字符串cur,上层字符串above,还有我们的HashMap。如果cur的大小为2,above的大小为1,那么说明当前已经达到金字塔的顶端了,已经搭出来了,直接返回true。否则看,如果上一层的长度比当前层的长度正好小一个,说明上一层也搭好了,我们现在去搭上上层,于是调用递归函数,将above当作当前层,空字符串为上一层,将调用的递归函数结果直接返回。否则表示我们还需要继续去搭above层,我们先算出above层的长度pos,然后从当前层的pos位置开始取两个字符,就是above层接下来需要搭的字符的基座字符,举个例子如下:

  1. D
  2. / \ / \
  3. A B C

我们看到现在above层只有一个D,那么pos为1,在cur层1位置开始取两个字符,得到"BC",即是D的下一个位置的字符的基座字符串base。取出了base后,如果HashMap中有映射,则我们遍历其映射的字符集合中的所有字符,对每个字符都调用递归函数,此时above字符串需要加上这个遍历到的字符,因为我们在尝试填充这个位置,如果有返回true的,那么当前递归函数就返回true了,否则最终返回false,参见代码如下:

解法一:

  1. class Solution {
  2. public:
  3. bool pyramidTransition(string bottom, vector<string>& allowed) {
  4. unordered_map<string, unordered_set<char>> m;
  5. for (string str : allowed) {
  6. m[str.substr(, )].insert(str[]);
  7. }
  8. return helper(bottom, "", m);
  9. }
  10. bool helper(string cur, string above, unordered_map<string, unordered_set<char>>& m) {
  11. if (cur.size() == && above.size() == ) return true;
  12. if (above.size() == cur.size() - ) return helper(above, "", m);
  13. int pos = above.size();
  14. string base = cur.substr(pos, );
  15. if (m.count(base)) {
  16. for (char ch : m[base]) {
  17. if (helper(cur, above + string(, ch), m)) {
  18. return true;
  19. }
  20. }
  21. }
  22. return false;
  23. }
  24. };

下面来看一种迭代的写法,这是一种DP的解法,建立一个三维的dp数组,其中dp[i][j][ch]表示在金字塔(i, j)位置上是否可以放字符ch,金字塔的宽和高已经确定了,都是n。每个位置对应着nxn的数组的左半边,如下所示:

F _ _
D E _
A B C

除了底层,每个位置可能可以放多个字符,所以这里dp数组是一个三维数组,第三维的长度为7,因为题目中限定了字母只有A到G共7个,如果dp值为true,表示该位置放该字母,我们根据bottom字符串来初始化dp数组的底层。这里还是需要一个HashMap,不过跟上面的解法略有不同的是,我们建立上方字母跟其能放的基座字符串集合的映射,因为一个字母可能可以放多个位置,所以用个集合来表示。然后我们就开始从倒数第二层开始往顶部更新啦,对于金字塔的每个位置,我们都遍历A到G中所有的字母,如果当前字母在HashMap中有映射,则我们遍历对应的基座字符串集合中的所有字符串,基座字符串共有两个字母,左边的字母对应的金字塔中的位置是(i + 1, j),右边的字母对应的位置是(i + 1, j + 1),我们只要在这两个位置上分别查询对应的字母的dp值是否为true,是的话,说明当前位置有字母可以放,我们将当前位置的字母对应的dp值赋值为true。这样,当我们整个更新完成了之后,我们只要看金字塔顶端位置(0, 0)是否有字母可以放,有的话,说明可以搭出金字塔,返回true,否则返回false,参见代码如下:

解法二:

  1. class Solution {
  2. public:
  3. bool pyramidTransition(string bottom, vector<string>& allowed) {
  4. int n = bottom.size();
  5. vector<vector<vector<bool>>> dp(n, vector<vector<bool>>(n, vector<bool>(, false)));
  6. unordered_map<char, unordered_set<string>> m;
  7. for (string str : allowed) {
  8. m[str[]].insert(str.substr(, ));
  9. }
  10. for (int i = ; i < n; ++i) {
  11. dp[n - ][i][bottom[i] - 'A'] = true;
  12. }
  13. for (int i = n - ; i >= ; --i) {
  14. for (int j = ; j <= i; ++j) {
  15. for (char ch = 'A'; ch <= 'G'; ++ch) {
  16. if (!m.count(ch)) continue;
  17. for (string str : m[ch]) {
  18. if (dp[i + ][j][str[] - 'A'] && dp[i + ][j + ][str[] - 'A']) {
  19. dp[i][j][ch - 'A'] = true;
  20. }
  21. }
  22. }
  23. }
  24. }
  25. for (int i = ; i < ; ++i) {
  26. if (dp[][][i]) return true;
  27. }
  28. return false;
  29. }
  30. };

参考资料:

https://leetcode.com/problems/pyramid-transition-matrix/discuss/113075/DP-O(n2-*-m)

https://leetcode.com/problems/pyramid-transition-matrix/discuss/113036/A-map-based-solution-based-on-memoization

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Pyramid Transition Matrix 金字塔转变矩阵的更多相关文章

  1. LC 756. Pyramid Transition Matrix

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

  2. [LeetCode] 59. Spiral Matrix II 螺旋矩阵 II

    Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. For ...

  3. [Swift]LeetCode756. 金字塔转换矩阵 | Pyramid Transition Matrix

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

  4. 【LeetCode】756. Pyramid Transition Matrix 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 日期 题目地址:https://leetco ...

  5. 【leetcode】756. Pyramid Transition Matrix

    题目如下: We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, ...

  6. LeetCode 73. Set Matrix Zeros(矩阵赋零)

    Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. click ...

  7. LeetCode 54. Spiral Matrix(螺旋矩阵)

    Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral or ...

  8. [LeetCode] 885. Spiral Matrix III 螺旋矩阵之三

    On a 2 dimensional grid with R rows and C columns, we start at (r0, c0) facing east. Here, the north ...

  9. leetcode[73] Set Matrix Zeroes 将矩阵置零

    给定一个矩阵,把零值所在的行和列都置为零.例如: 1 2 3 1 3 1 1 1 操作之后变为 1 3 0 0 0 1 1 方法1: 赋值另存一个m*n的矩阵,在原矩阵为零的值相应置新的矩阵行和列为零 ...

随机推荐

  1. 使用责任链模式消除if分支实践

    之前接手过一个车辆监控的工具,接受第三方推送过来的车辆状态数据然后入库.车辆状态一共有8种之多,每种状态都需要做不同 处理操作.刚接手这份代码时,针对此处处理,是庞大的if-else结构,if-els ...

  2. 四十六、android中的Bitmap

    四十六.android中的Bitmap: http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html 四十七.实现调用Android ...

  3. oracle、导出、导入

    一.数据库导入: No1.查询所有表中那些是空表. select table_name from user_tables where NUM_ROWS=0; No2.拼接字符串生成SQL执行语句. s ...

  4. 关于如何在mac系统上安装Git并在码市上建立项目

    对Git一窍不通,为了在mac系统上安装Git,查了很多资料,走了很多弯路,一切搞定后发现其实很简单. 1.在https://brew.sh上按要求安装Homebrew. 2.在电脑终端键入brew ...

  5. 20162318 实验四 Android程序设计

    北京电子科技学院(BESTI) 实 验 报 告 课程:程序设计与数据结构 班级:1623班 姓名:张泰毓 指导老师:娄老师.王老师 实验日期:2017年5月26日 实验密级:非密级 实验器材:带Lin ...

  6. 百词斩APP分析

    一.调研 1.第一次上手   第一次使用,可以使用微信和qq登录感觉挺不错的不然又要注册有点麻烦,在功能上,用户可以针对自身选择不同水平的英语背单词,然后有多钟方式对自己的听力和单词翻译进行提升.在u ...

  7. [Android FrameWork 6.0源码学习] View的重绘ViewRootImpl的setView方法

    博客首页:http://www.cnblogs.com/kezhuang/p/ 本篇文章来分析一下WindowManager的后续工作,也就是ViewRootImpl的setView函数的工作 /i* ...

  8. HDFS的7个设计特点

    1.Block的放置:默认不配置.一个Block会有三份备份,一份放在NameNode指定的DataNode,另一份放在与指定DataNode非同一Rack上的DataNode,最后一份放在与指定Da ...

  9. installutil 安装windows service

    1:路径:C:\Windows\Microsoft.NET\Framework\v4.0.30319 2:执行指令:C:\Windows\Microsoft.NET\Framework\v4.0.30 ...

  10. emqtt 试用(二)验证 emq 和 mosquito 的共享订阅

    本地订阅(Local Subscription) 本地订阅(Local Subscription)只在本节点创建订阅与路由表,不会在集群节点间广播全局路由,非常适合物联网数据采集应用. 使用方式: 订 ...