思路:当前dp[i][j]来自dp[i-1][j] 和 dp[i][j-1]
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp = [[0] * n] * m
dp[0][0] = 1
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
right = dp[i][j-1] if j-1 >= 0 else 0
top = dp[i-1][j] if i-1 >= 0 else 0
dp[i][j] = top + right
return dp[m-1][n-1]
题目链接:63. 不同路径 II - 力扣(LeetCode)
思路:针对上一题做一些障碍物的判断就行
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0] * n] * m
if obstacleGrid[0][0] == 1:
return 0
dp[0][0] = 1
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
continue
right = dp[i-1][j] if i-1 >= 0 and obstacleGrid[i-1][j] != 1 else 0
top = dp[i][j-1] if j-1 >= 0 and obstacleGrid[i][j-1] != 1 else 0
dp[i][j] = right + top if obstacleGrid[i][j] != 1 else 0
return dp[m-1][n-1]