leet笔记-63.不同路径II

时间:2022-07-24
本文章向大家介绍leet笔记-63.不同路径II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

leet笔记-63.不同路径II

题目

思路:

【参考】leetcode官方解释

关键点1:只能向右或者向下

关键点2:有障碍物为1, 无障碍物为0

根据 关键点1 和 关键点2 来确定动态规划的步骤:

  1. 定义DP数组 可以直接利用题目中的obstacleGrid
  2. 找出关系数组元素间的关系式 初始化好之后,发现动态方程: 遍历时:
    1. 若当前为0。那么,直接计算动态方程下的计算过程
    2. 若当前不为0。那么,直接置该位置的值为0
  3. 找出初始值 利用动态规划解题的时候,初始化首行和首列的时候,障碍物1后面的都不可达

那么,按照以上点给出代码

class Solution(object):
   # 时间复杂度: O(mxn)
   # 空间复杂度: O(mxn)
   def uniquePathsWithObstacles1(self, obstacleGrid):
       # row number
       m = len(obstacleGrid)
       # column number
       n = len(obstacleGrid[0])

       # If the starting cell has an obstacle, then simply return as there would be
       # no paths to the destination.
       # so, give the result for 0
       if obstacleGrid[0][0] == 1:
           return 0

       # Number of ways of reaching the starting cell = 1.
       obstacleGrid[0][0] = 1

       # Filling the values for the first column
       for clo in range(1, m):
           obstacleGrid[clo][0] = int(obstacleGrid[clo][0] == 0 and obstacleGrid[clo-1][0] == 1)

       # Filling the values for the first row
       for row in range(1, n):
           obstacleGrid[0][row] = int(obstacleGrid[0][row] == 0 and obstacleGrid[0][row-1] == 1)

       # start from the cell[1][1] fill up the values
       # DP way of reach: cell[i][j] = cell[i-1][j] + cell[i][j-1]
       for i in range(1, m):
           for j in range(1, n):
               if obstacleGrid[i][j] == 0:
                   obstacleGrid[i][j] = obstacleGrid[i-1][j] + obstacleGrid[i][j-1]
               else:
                   obstacleGrid[i][j] = 0

       return obstacleGrid[m-1][n-1]

时间复杂度: O(mxn) 遍历obstacleGrid的每一个格子,所需要的时间度量为m*n

空间复杂度: O(1), 没有产生额外的数据存放空间