题目如下:

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'}.

解题思路:我的方法是采用DFS,对于判断是否的题目,用DFS的效率要高于BFS。题目中有一点好像没有说明,就是allowed里面的同一个元素可以用多次。遍历allowed,先找出前两个字符与bottom前两个字符相同的元素;然后bottom去掉第一位,再去allowed中找出前两个字符与bottom前两个字符相同的元素,循环直至bottom长度变成1为止;接下来令bottom等于第一轮中找到的所有的元素的最后一个字符拼接组成的新的字符串,重复第一轮的操作。同时每找到一个可以组成bottom的元素,用一个变量used记录个数,直到userd =  len(bottom) * (len(bottom) -1 )/2 表示可以组成如题目要求的bottom。为什么?因为要组成三角形所需的元素个数正好等于 (1+2+3....+最底部bottom的长度)。

代码如下:

class Solution(object):
def pyramidTransition(self, bottom, allowed):
"""
:type bottom: str
:type allowed: List[str]
:rtype: bool
"""
queue = []
dic = {}
for i in allowed:
if bottom[:2] == i[:2]:
queue.append((bottom[1:],i[-1],1))
if i[:2] not in dic:
dic[i[:2]] = [i]
else:
dic[i[:2]].append(i) while len(queue) > 0:
#print len(queue)
bot,path,used = queue.pop(0)
#print used
if used == len(bottom) * (len(bottom) -1 )/2:
return True
elif len(bot) < 2:
queue.insert(0,(path,'',used+1))
else:
if bot[:2] in dic:
for i in dic[bot[:2]]:
queue.insert(0,(bot[1:], path + i[-1], used + 1))
return False

【leetcode】756. Pyramid Transition Matrix的更多相关文章

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

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

  2. 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 ...

  3. 【LeetCode】566. Reshape the Matrix 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 变长数组 求余法 维护行列 相似题目 参考资料 日期 ...

  4. 【LeetCode】519. Random Flip Matrix 解题报告(Python)

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

  5. 【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 ...

  6. 【leetcode】 Search a 2D Matrix (easy)

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  7. 【leetcode】566. Reshape the Matrix

    原题 In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a ne ...

  8. 【leetcode】519. Random Flip Matrix

    题目如下: You are given the number of rows n_rows and number of columns n_cols of a 2D binary matrix whe ...

  9. 【LeetCode】01 Matrix 解题报告

    [LeetCode]01 Matrix 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/01-matrix/#/descripti ...

随机推荐

  1. 【leetcode】659. Split Array into Consecutive Subsequences

    题目如下: 解题思路:本题可以维护三个字典,dic_1保存没有组成序列的单元素,dic_2保存组成了包含两个元素的序列中的较大的元素,dic_3保存组成了包括三个或者三个以上元素的序列中的最大值.因为 ...

  2. 前端必用正则(js)

    手机号 /^1((3[\d])|(4[5,6,9])|(5[0-3,5-9])|(6[5-7])|(7[0-8])|(8[1-3,5-8])|(9[1,8,9]))\d{8}$/ 大写字母 /^[A- ...

  3. linux根据进程名获取PID

    经常需要Kill多个进程,这些进程包含共同的关键字,可以用一条命令Kill掉它们. ps aux | grep "common" |grep -v grep| cut -c 9-1 ...

  4. Java Web学习总结(11)JDBC

    一,简介 JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的 ...

  5. 【WebSocket】WebSocket消息推送

    准备使用WebSocket实现Java与Vue或者安卓间的实时通信,实现私密聊天.群聊.查询下资料备用. WebSocket客户端 websocket允许通过JavaScript建立与远程服务器的连接 ...

  6. 10.14 socket 网络编程

    简单的例子 socket客户端 import socket client = socket.socket() #声明socket类型,同时生成socket连接对象 client.connect(('l ...

  7. jquery动态修改带有important的样式方法

    $('.el-card').css("background", "#fff !important");(不起作用的) 改为: $('.el-card').css ...

  8. js获取URL地址的参数

    function getQueryString(name) { var reg = new RegExp("(^|&)" + name + "=([^&] ...

  9. Microsoft Office Excel

    解除合并,并复制原始值到每一个解除合并后的单元格 对齐方式 -> 合并后居中 -> 取消单元格合并 编辑 -> 查找和选择 -> 定位条件 -> 空值 输入=然后按↑选择 ...

  10. xml解析用正则解决没有标签的文本的解析不出异常

    如  <q>sasas<w>eqwe</w>ddas</q> package com.people.xmlToSql; import java.io.F ...