当前位置:   article > 正文

代码随想录算法训练营day42 | 62.不同路径、63. 不同路径 II

代码随想录算法训练营day42 | 62.不同路径、63. 不同路径 II

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数组
  1. class Solution:
  2. def uniquePaths(self, m: int, n: int) -> int:
  3. dp = [[1] * n for _ in range(m)]
  4. for i in range(1, m):
  5. for j in range(1, n):
  6. dp[i][j] = dp[i-1][j] + dp[i][j-1]
  7. return dp[-1][-1]

可以使用一维数组优化空间复杂度

  1. class Solution:
  2. def uniquePaths(self, m: int, n: int) -> int:
  3. dp = [1] * n
  4. for i in range(1, m):
  5. for j in range(1, n):
  6. dp[j] += dp[j-1]
  7. 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数组
  1. class Solution:
  2. def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
  3. m = len(obstacleGrid)
  4. n = len(obstacleGrid[0])
  5. dp = [[0] * n for _ in range(m)]
  6. for i in range(m):
  7. if obstacleGrid[i][0] == 0:
  8. dp[i][0] = 1
  9. else:
  10. break
  11. for j in range(n):
  12. if obstacleGrid[0][j] == 0:
  13. dp[0][j] = 1
  14. else:
  15. break
  16. for i in range(1, m):
  17. for j in range(1, n):
  18. if obstacleGrid[i][j] == 1:
  19. dp[i][j] = 0
  20. else:
  21. dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
  22. return dp[-1][-1]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/762451
推荐阅读
相关标签
  

闽ICP备14008679号