Leetcode-5.7[LCP 06。拿硬币,572。另一棵树的子树,LCP 07。传输信息](Python实现),leetcode57LCP06,一个,LCP07,传递信息,python


题目1

在这里插入图片描述

题解1

class Solution:
    def minCount(self, coins: List[int]) -> int:
        """
        贪心算法
        """
        count = 0
        for coin in coins:
            num, mod = divmod(coin,2)
            count += num
            count += mod
        return count

    def minCount(self, coins: List[int]) -> int:
        """
        动态规划
        """
        # 子问题:DP[i]指的是到第i个数时最少的拿完次数
        # 子问题间的关系: DP[i] = DP[i-1] + A[i]//2 + A[i]%2
        # 边界条件: DP[0] = 0
        # 列表
        #         i      0       1       2       3
        #       A[i]             4       2       1
        #       DP[i]    0       2       3       4
        n = len(coins)
        DP = [None]*(n+1)
        DP[0] = 0
        for i in range(1, n+1):
            DP[i] = DP[i-1] + coins[i-1]//2 + coins[i-1]%2
        return DP[-1]

附上题目链接

题目2

在这里插入图片描述

题解2

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
        if not s and not t:
            return True
        if not s or not t:
            return False
        # 返回当前值和t是否相等,或上它的左右子树,有一个为True整体为True
        return self.isSameTree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)

    def isSameTree(self, s, t):
        if not s and not t:
            return True
        if not s or not t:
            return False
        return s.val == t.val and self.isSameTree(s.left, t.left) and self.isSameTree(s.right, t.right)

附上题目链接

题目3

在这里插入图片描述

题解3

class Solution:
    # 动态规划
    def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
        """
        子问题: DP[i-1][j] 表示数组的第i-1轮传递给编号j的人的方案数
        子问题间的关系: 若能传递给编号y的玩家编号为x1,x2,x3....,则第i轮传递给y玩家的方程为:
                DP[i][y] = sum(DP[i-1][x1],DP[i-1][x2],DP[i-1][x3])
            即: DP[i][y] += DP[i-1][x]

        边界条件: DP[0][0] = 1

        示例1:
        # 第一轮,只记从编号0开始,除了将0轮的第一个设置为1,其他均为0
        [1,0,0,0,0]  [0,0,1,0,1] [0,0,0,0,0] [0,0,0,0,0]

        # 第二轮,只看从起始编号一路过来的
        [1,0,0,0,0]  [0,0,1,0,1] [1,1,0,1,0] [0,0,0,0,0]

        # 第三轮,同上
        [1,0,0,0,0]  [0,0,1,0,1] [1,1,0,1,0] [0,0,1,0,3]
        """
        dp = [[0]*n for t in range(0,k+1)]
        dp[0][0] = 1

        for i in range(0,k):
            for x, y in relation:
                dp[i+1][y] += dp[i][x]
        # dp[-1][-1] 指的是最后一轮最后一个
        return dp[-1][-1]

附上题目链接