赞
踩
509. 斐波那契数
dp[i] = dp[i-1] + dp[i-2]
class Solution:
def fib(self, n: int) -> int:
if n==0 : return 0
dp0 = 1
dp1 = 1
for i in range(2,n):
r = dp0 + dp1
dp0 = dp1
dp1 = r
return dp1
70. 爬楼梯
同1
class Solution:
def climbStairs(self, n: int) -> int:
dp0 = 1
dp1 = 1
for i in range(2,n+1):
r = dp0 + dp1
dp0 = dp1
dp1 = r
return dp1
746. 使用最小花费爬楼梯
dp[i]表示到第i阶的最小花费
dp[i] = min( dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])
dp0 = dp1 = 0
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0,0]
for i in range(2,len(cost)+1):
dp.append( min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2]) )
return dp[-1]
62.不同路径
每个格子只能由上格和左格走到
dp[i][j] = dp[i-1][j] + dp[i][j-1]
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1]*n]*m
for i in range(1,m):
for j in range(1,n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
63. 不同路径 II
初始化时,首行首列遇到障碍物后续都为0,其余部分障碍物为0
class Solution: def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: if obstacleGrid[0][0]==1: return 0 for i in range(len(obstacleGrid)): if obstacleGrid[i][0] == 0: obstacleGrid[i][0] = 1 else: for j in range(i,len(obstacleGrid)): obstacleGrid[j][0] = 0 break for i in range(1,len(obstacleGrid[0])): if obstacleGrid[0][i] == 0: obstacleGrid[0][i] = 1 else: for j in range(i,len(obstacleGrid[0])): obstacleGrid[0][j] = 0 break for i in range(1,len(obstacleGrid)): for j in range(1,len(obstacleGrid[0])): if obstacleGrid[i][j]==0: obstacleGrid[i][j] = 1 else: obstacleGrid[i][j] = 0 for i in range(1,len(obstacleGrid)): for j in range(1,len(obstacleGrid[0])): if obstacleGrid[i][j]!=0: obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1] return obstacleGrid[-1][-1]
343. 整数拆分
dp[i]表示拆分i可得的最大乘积
dp[i] = max( j*(i-j), j*dp[i-j], dp[i])
dp[0]=dp[1]=1
class Solution:
def integerBreak(self, n: int) -> int:
dp = [1]*(n+1)
for i in range(2,n+1):
for j in range(1,i):
dp[i] = max( j*(i-j), j*dp[i-j], dp[i] )
return dp[-1]
96.不同的二叉搜索树
dp[i]表示i个节点的二叉树的构成方式总数
dp[i] = dp[左树]*dp[右树] 的和
例如dp[3]=dp[0]*dp[2]+dp[1]*dp[1]+dp[2]*dp[0]
class Solution:
def numTrees(self, n: int) -> int:
dp = [0]*(n+1)
dp[0],dp[1] = 1,1
for i in range(2,n+1):
for j in range(1,i+1):
dp[i] += dp[j-1]*dp[i-j]
return dp[-1]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。