目录
注意:
53. 最大子序和
120. 三角形最小路径和
63. 不同路径 II
91. 解码方法
198. 打家劫舍
300. 最长上升子序列
72. 编辑距离
518. 零钱兑换 II
和b站up主大雪菜一起刷的https://www.bilibili.com/video/BV15441117yb
思路:
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
res = - float('INF')
last = 0
for num in nums:
now = max(last, 0) + num
last = now
res = max(res, now)
return res
思路:
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
rows = len(triangle)
cols = len(triangle)
dp = [[float('INF')]*cols for _ in range(rows)]
dp[0][0] = triangle[0][0]
if rows==1:
return dp[0][0]
for i in range(1, rows):
for j in range(i+1):
if j > 0:
dp[i][j] = min(dp[i][j], dp[i-1][j-1] + triangle[i][j])
if j < i:
dp[i][j] = min(dp[i][j], dp[i-1][j] + triangle[i][j])
res = float('INF')
for i in range(cols):
res = min(res, dp[rows-1][i])
return res
思路:
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
rows,cols = len(obstacleGrid), len(obstacleGrid[0])
dp = [[0]*cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
# 遇到障碍
if obstacleGrid[i][j]==1:
continue
# 左上角
if not i and not j:
dp[i][j] = 1
if i>0:
dp[i][j] += dp[i-1][j]
if j>0:
dp[i][j] += dp[i][j-1]
return dp[rows-1][cols-1]
思路:
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
dp = [0]*(n+1)
dp[0] = 1
for i in range(1, n+1):
# 最后一位可以表示
if s[i-1]!='0':
dp[i] += dp[i-1]
if i>=2:
sum_ = (ord(s[i-2])-ord('0'))*10 + (ord(s[i-1])-ord('0'))
# 最后两位可以表示
if 10<=sum_<=26:
dp[i] += dp[i-2]
return dp[n]
思路:
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
f, g = [0]*(n+1),[0]*(n+1)
for i in range(1, n+1):
f[i] = max(f[i-1], g[i-1])
g[i] = f[i-1]+nums[i-1]
return max(f[n], g[n])
思路:
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
if not nums:
return 0
n = len(nums)
dp = [1]*n
res = 1
for i in range(n):
for j in range(i):
if nums[j]
思路:
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
n = len(word1)
m = len(word2)
dp = [[0]*(m+1) for _ in range(n+1)]
# 边界 word1匹配上word2第0个位置也就是空 需要进行i次删除
for i in range(n+1):
dp[i][0] = i
for i in range(m+1):
dp[0][i] = i
for i in range(1, n+1):
for j in range(1, m+1):
# 插入 删除
dp[i][j] = min(dp[i-1][j], dp[i][j-1])+1
dp[i][j] = min(dp[i][j], dp[i-1][j-1]+(word1[i-1]!=word2[j-1]))
return dp[n][m]
思路:
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
n = len(coins)
dp = [[0]*(amount+1) for _ in range(n+1)]
dp[0][0]=1
for i in range(1, n+1):
for j in range(amount+1):
dp[i][j] = dp[i-1][j]
if j >= coins[i-1]:
dp[i][j] += dp[i][j-coins[i-1]]
return dp[n][amount]