LeetCode题解(0756):金字塔转换矩阵(Python)

题目:原题链接(中等)

标签:深度优先搜索、位运算

解法时间复杂度空间复杂度执行用时
Ans 1 (Python) O ( 7 N ) O(7^N) O(7N) O ( N 2 ) O(N^2) O(N2)56ms (14.49%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def pyramidTransition(self, bottom: str, allowed: List[str]) -> bool:
        allows = collections.defaultdict(list)
        for allow in allowed:
            allows[allow[0:2]].append(allow[2])

        def dfs1(now_level):
            if len(now_level) == 1:
                return True
            for next_level in dfs2(now_level, 0, ""):
                if dfs1(next_level):
                    return True
            return False

        def dfs2(now_level, i, next_level):
            if i == len(now_level) - 1:
                return [next_level]
            else:
                ch1, ch2 = now_level[i], now_level[i + 1]
                if ch1 + ch2 not in allows:
                    return []
                else:
                    res = []
                    for ch3 in allows[ch1 + ch2]:
                        res.extend(dfs2(now_level, i + 1, next_level + ch3))
                    return res

        return dfs1(bottom)
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

打赏
文章很值,打赏犒劳作者一下
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页

打赏

长行

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者