# 动态规划题目汇总练习

class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# dp[i][j]表示到达i,j的最多路径
# 状态转移方程：dp[i][j] = dp[i-1][j]+dp[i][j-1]
# 边界值：第一行、第一列都为1，因为在第一行只能往左走，在第一列只能往下走。
dp=[[1 for i in range(n)] for j in range(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[-1][-1]

class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m,n = len(obstacleGrid),len(obstacleGrid[0])
# 起始位置
if obstacleGrid[0][0] == 1:
return 0

# 第一行
# 如果有障碍物，则设置当前位置为0；否则为前一个位置的值
obstacleGrid[0][0]=1
for i in range(1,m):
if obstacleGrid[i][0] == 1:
obstacleGrid[i][0] = 0
else:
obstacleGrid[i][0] = obstacleGrid[i-1][0]

# 第一列
for i in range(1,n):
if obstacleGrid[0][i] == 1:
obstacleGrid[0][i] = 0
else:
obstacleGrid[0][i] = obstacleGrid[0][i-1]

for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j] == 1:
obstacleGrid[i][j] = 0
else:
obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
return obstacleGrid[-1][-1]

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客