題目1
題解1
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root is None:
return False
sum -= root.val
if not root.left and not root.right:
return sum == 0
return self.hasPathSum(root.left, sum) or self.hasPathSum(root.right, sum)
附上題目鏈接
題目2
題解2
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = []
for i in range(numRows):
now = [1]*(i+1)
if i >= 2:
for j in range(1,i):
now[j] = pre[j-1] + pre[j]
res += [now]
pre = now
return res
def generate(self, num_rows):
triangle = []
for row_num in range(num_rows):
row = [None for _ in range(row_num+1)]
row[0], row[-1] = 1, 1
for j in range(1, len(row)-1):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]
triangle.append(row)
return triangle
附上題目鏈接
題目3
題解3
class Solution:
def maxProfit(self, prices: List[int]) -> int:
n = len(prices)
if n <= 1:
return 0
mid = n//2
left = prices[:mid]
right = prices[mid:]
left_price = self.maxProfit(left)
right_price = self.maxProfit(right)
left_right_price = max(right) - min(left)
return max(left_price, right_price, left_right_price)
def maxProfit(self, prices: List[int]) -> int:
"""
input: [7,1,5,3,6,4]
子問題:DP[i]爲到第i個元素時股票賺的最多
子問題之間的關係: DP[i] = max(DP[i-1], A[i]- min_price]) 用min記錄下的到i個元素的最小值下標
邊界條件: DP[0] = 0
建表: i 0 1 2 3 4 5
A[i] 7 1 5 3 6 4
min_price 7 1 1 1 1 1
D[i] 0 0 4 4 5 5
"""
n = len(prices)
if n <= 0:
return 0
DP = [None]*n
DP[0] = 0
min_price = prices[0]
for i in range(1,n):
min_price = min(min_price, prices[i])
DP[i] = max(DP[i-1],prices[i]-min_price)
print(min_price)
return max(DP)
附上題目鏈接