作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/pyramid-transition-matrix/description/

题目描述

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:

  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中的"XYD",那么就是在X和Y的基础上可以增加一个D字符。

解题方法

回溯法

刚开始感觉到很难,是因为没有建立好模型,这个其实是一个考察回溯法的题目。

首先,我们来分析一下这个问题的难点在哪里。一般的回溯法题目对于下一个转移状态是很明确告知的,比如常见的地图的4或者8个方向,但是这个题目的回溯转移是需要我们简单设计一下,那就是把两个连续的字符串能够生成的所有第三个字符放到列表里,当做我们下一个前进的方向。如果把这个转移状态设计好了,我们就很容易写出代码了。

我们在每层字符串作为底座的基础上,向上面建立新的一层。所以是个递归过程。建立的方式是通过允许的组合,这个组合是我们可以通过下面的这两块砖来获得上面可以累加什么砖的方式。

所以,用curr表示当前层,用above表示上层。当curr大小为2,above为1,那么金字塔完成。如果curr = above + 1,说明上面这层已经弄好了,下面使用above来作为当前层,继续递归。

如果上面两个都不满足,说明需要继续堆积above,做的方式是在应该继续堆积的位置上,找出能堆积哪些字符,并把这个字符堆积上去,做递归。

我犯了一个错误,是使用的map保存的是键值对,但是对于重复出现的情况就被替换掉了。因此使用list才行,代表了这两块砖上面允许堆积的砖。

代码如下:

class Solution(object):
def pyramidTransition(self, bottom, allowed):
"""
:type bottom: str
:type allowed: List[str]
:rtype: bool
"""
m = collections.defaultdict(list)
for triples in allowed:
m[triples[:2]].append(triples[-1])
return self.helper(bottom, "", m) def helper(self, curr, above, m):
if len(curr) == 2 and len(above) == 1:
return True
if len(above) == len(curr) - 1:
return self.helper(above, "", m)
pos = len(above)
base = curr[pos : pos+2]
if base in m:
for ch in m[base]:
if self.helper(curr, above + ch, m):
return True
return False

C++代码如下:

class Solution {
public:
bool pyramidTransition(string bottom, vector<string>& allowed) {
if (bottom.size() == 1) return true;
for (string& a : allowed) {
m_[a.substr(0, 2)].push_back(a[2]);
}
return helper(bottom, "", m_);
}
private:
unordered_map<string, vector<char>> m_;
bool helper(string pre, string cur, unordered_map<string, vector<char>>& m_) {
if (pre.size() == 2 && cur.size() == 1) return true;
if (pre.size() - cur.size() == 1)
return helper(cur, "", m_);
int pos = cur.size();
string next = pre.substr(pos, 2);
for (char cs : m_[next]) {
if (helper(pre, cur + cs, m_)) {
return true;
}
}
return false;
}
};

参考资料:

http://www.cnblogs.com/grandyang/p/8476646.html

日期

2018 年 9 月 6 日 —— 作息逐渐规律。
2019 年 1 月 25 日 —— 这学期最后一个工作日

【LeetCode】756. Pyramid Transition Matrix 解题报告(Python & C++)的更多相关文章

  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】54. Spiral Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 维护四个边界和运动方向 保存已经走过的位置 日期 题 ...

  3. 【LeetCode】867. Transpose Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 先构建数组再遍历实现翻转 日期 题目地址:https ...

  4. 【leetcode】756. Pyramid Transition Matrix

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

  5. 【LeetCode】766. Toeplitz Matrix 解题报告

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 方法一:两两比较 方法二:切片相等 方法三:判断每条 ...

  6. LeetCode 566 Reshape the Matrix 解题报告

    题目要求 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ...

  7. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

  8. LeetCode: Search a 2D Matrix 解题报告

    Search a 2D Matrix Write an efficient algorithm that searches for a value in an m x n matrix. This m ...

  9. 【LeetCode】378. Kth Smallest Element in a Sorted Matrix 解题报告(Python)

    [LeetCode]378. Kth Smallest Element in a Sorted Matrix 解题报告(Python) 标签: LeetCode 题目地址:https://leetco ...

随机推荐

  1. Go语言缺陷

    我为什么放弃Go语言 目录(?)[+] 我为什么放弃Go语言 有好几次,当我想起来的时候,总是会问自己:我为什么要放弃Go语言?这个决定是正确的吗?是明智和理性的吗?其实我一直在认真思考这个问题. 开 ...

  2. 从Redis分布式缓存实战入手到底层原理分析、面面俱到覆盖大厂面试考点

    概述 官方说明 Redis官网 https://redis.io/ 最新版本6.2.6 Redis中文官网 http://www.redis.cn/ 不过中文官网的同步更新维护相对要滞后不少时间,但对 ...

  3. day07 Linux配置修改

    day07 Linux配置修改 昨日回顾 1.系统目录 /etc :系统配置目录 /bin-> /usr/bin :保存常用命令的目录 /root :超级管理员目录 /home :普通管理员目录 ...

  4. 20. VIM命令操作技巧

    V可视化选中当前行,根据光标可多行 ctrl+v 可视化块 v可视化根据光标 行间移动 快速增删改查 d 0 删除当前位置到行首 d $ 删除当前位置到行尾 d  t  (" ] ) )符号 ...

  5. C++自定义字符串类

    //header.h #ifndef _HEADER_H #define _HEADER_H #define defaultSize 128 #include<iostream> #inc ...

  6. linux修改文件权限命令

    先看个实例: [root@local opt]#ls -al ls -al 命令是列出目录的所有文件,包括隐藏文件.隐藏文件的文件名第一个字符为'.' -rw-r--r--  1 root root  ...

  7. java代码定时备份mysql数据库及注意事项——基于 springboot

    源码地址: https://gitee.com/kevin9401/BackUpDataBase git 拉取: https://gitee.com/kevin9401/BackUpDataBase. ...

  8. linux 定时导出sql查询结果文件

    如果想在服务器端生成sql查询结果的txt文件. 大体思路就是: 1.创建一个到处txt文件的sql脚本. set ARRAYSIZE 50 --从数据库往客户端一次发送记录数 set linesiz ...

  9. 连接 MySQL 数据库出现问题:The server time zone value ‘�й���׼ʱ��‘ is unrecogni....

    出现问题 The server time zone value '�й���׼ʱ��' is unrecogni.... 解决方案 在 URL 后面加上 ?serverTimezone=UTC 如下: ...

  10. String直接赋值与使用new String的区别

    在研究String直接赋值与new String的区别之前我们需要先了解java中的字符串常量池的概念 字符串常量池 String类是我们平常项目中使用频率非常高的一种对象类型,jvm为了提升性能和减 ...