62.不同路径
- 确定dp数组及其下标的含义:dp[i][j]代表机器人到达i行j列时不同的路径数
- 确定递推公式:dp[i][j] = dp[i-1][j] + dp[i][j-1]
- dp数组的初始化:dp[0][j] = 1 dp[i][0] = 1
- 确定遍历顺序:从前向后
- 举例推导dp数组
python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n for _ 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]
可以使用一维数组优化空间复杂度
python
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [1] * n
for i in range(1, m):
for j in range(1, n):
dp[j] += dp[j-1]
return dp[-1]
63. 不同路径 II
- 确定dp数组以及下标的含义:dp[i][j]代表到达第i行第j列的不同路径数
- 确定递推公式:if obstacleGrid[i][j] == 1: dp[i][j] = 0 else: dp[i][j] = dp[i-1][j] + dp[i][j-1]
- dp数组的初始化:第0行和第0列都需要初始化为1,遇到障碍物后后续都初始化为0
- 确定遍历顺序:从前向后遍历
- 举例推导dp数组
python
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[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:
dp[i][j] = 0
else:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
return dp[-1][-1]