作者: 负雪明烛
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. 9. Delete Node in a Linked List

    Write a function to delete a node (except the tail) in a singly linked list, given only access to th ...

  2. mysql数据定义语言DDL

    库的管理 创建 create 语法:create database 库名 [character set 字符集] # 案例:创建库 create database if not exists book ...

  3. 零基础学习java------day16-----文件,递归,IO流(字节流读写数据)

    1.File 1.1 构造方法(只是创建已经存在文件的对象,并不能创建没有的文件) (1)public File(String pathname) (2)public File(String pare ...

  4. 双向链表——Java实现

    双向链表 链表是是一种重要的数据结构,有单链表和双向链表之分:本文我将重点阐述不带头结点的双向链表: 不带头结点的带链表 我将对双链表的增加和删除元素操作进行如下解析 1.增加元素(采用尾插法) (1 ...

  5. vue中vuex的五个属性和基本用法

    VueX 是一个专门为 Vue.js 应用设计的状态管理构架,统一管理和维护各个vue组件的可变化状态(你可以理解成 vue 组件里的某些 data ). Vuex有五个核心概念: state, ge ...

  6. springmvc中的异常处理方法

    //1.自定义异常处理类       2.编写异常处理器    3.配置异常处理器 package com.hope.exception;/** * 异常处理类 * @author newcityma ...

  7. 团队协作项目——SVN的使用

    参考文献:https://www.cnblogs.com/rwh871212/p/6955489.html 老师接了一个新项目,需要团队共同完成开发任务,因此需要SVN.SVN是C/S架构: 1.服务 ...

  8. 『与善仁』Appium基础 — 23、操作滑动的方式

    目录 1.swipe滑动 2.scroll滑动 3.drag拖拽事件 4.滑动方法小结 5.拓展:多次滑动 6.综合练习 在Appium中提供了三种滑动的方式,swipe滑动.scroll滑动.dra ...

  9. podman wsl2在windows重启后出错

    1. error joining network namespace for container 如果没有先停止容器就重启windows,极大概率就会出现这个问题 解决方法 先停止停止的容器再启动已退 ...

  10. 1、Spring简介及IOC入门案例

    一.Spring框架介绍 1.介绍 Spring框架是由于软件开发的复杂性而创建的.Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情.然而,Spring的用途不仅仅限于服务 ...