62.不同路径
首先理解题意,将该题分解为一个组合问题,然后再直接使用python的math
模块中的函数comb
函数
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
return comb(m+n-2,m-1)
或者使用动态规划的思想
我们将dp[i][j] = dp[i-1][j]+dp[i][j-1]
状态表示为到达(i,j)
位置时的最多路径
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1]*n] +[[1]+[0]*(n-1)for _ in range(m-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[-1][-1]
63.不同路径II
错误思路:没有考虑边界情况
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[1]*n]+[[1]+[0]*(n-1) for _ in range(m-1)]
# return dp
for i in range(1,m):
for j in range(1,n):
if obstacleGrid[i][j] != 0:
dp[i][j] = -1
dp[i][j] = max(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 = len(obstacleGrid)
n = len(obstacleGrid[0])
# dp = [[1]*n]+[[1]+[0]*(n-1) for _ in range(m-1)]
dp = [[0]*n for _ in range(m)]
if obstacleGrid[0][0] == 0:
dp[0][0] = 1
# return dp
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
dp[i][j] = 0
else:
if i > 0:
dp[i][j] += dp[i-1][j]
if j > 0:
dp[i][j] += dp[i][j-1]
return dp[-1][-1]