题目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:
"""
动态规划
"""
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
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
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]
return dp[-1][-1]
附上题目链接