62.不同路徑
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
table = [[0]*n]*m
for x in range(n):
table[0][x] = 1
for y in range(m):
table[y][0] = 1
for y in range(1, m):
for x in range(1, n):
table[y][x] = table[y-1][x] + table[y][x-1]
return table[-1][-1]
63. 不同路徑 II
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
if obstacleGrid[m - 1][n - 1] == 1 or obstacleGrid[0][0] == 1:
return 0
dp = [[0] * n for _ in range(m)]
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] == 1:
continue
else:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[m-1][n-1]