题目一
上边、左边初始化为1
采用求和进行dp运算
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp =[[0]*n for _ in range(m)]
for i in range(m):
dp[i][0] = 1
for j in range(n):
dp[0][j] = 1
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]
第二题
上题变种,
初始化策略要改变,遇到障碍后,之后的都是0
dp更新策略改变 ,遇到障碍跳过
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0] * n for _ in range(m)]
if obstacleGrid[0][0]==1 or obstacleGrid[m-1][n-1]==1:
return 0
for i in range(m):
if obstacleGrid[i][0]==0:
dp[i][0] = 1
else:
break
for j in range(n):
if obstacleGrid[0][j]==0:
dp[0][j] = 1
else:
break
for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j] == 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]
题目三:
dp[i] 代表将 i 拆分后的乘积最大值,
计算方式有两种:j x i-j
或者 j x dp[i-j]
本质上也是二元的思维,
class Solution(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n+1)
dp[2] = 1
for i in range(3,n+1):
for j in range(1,i):
dp[i] = max(dp[i],j*(i-j),j*dp[i-j])
return dp[n]