• [leetcode DP]63. Unique Paths II


    Follow up for "Unique Paths":

    Now consider if some obstacles are added to the grids. How many unique paths would there be?

    An obstacle and empty space is marked as 1 and 0 respectively in the grid.

    For example,

    There is one obstacle in the middle of a 3x3 grid as illustrated below.

    [
      [0,0,0],
      [0,1,0],
      [0,0,0]
    ]
    

    The total number of unique paths is 2.

    障碍物对应的dp表中设为0即可,为了使代码简洁,多加了两行dp[i][0]和dp[0][j]

     1 class Solution(object):
     2     def uniquePathsWithObstacles(self, obstacleGrid):
     3         m,n = len(obstacleGrid),len(obstacleGrid[0])
     4         dp = [[0 for j in range(n+1)] for i in range(m+1)]
     5         dp[0][1] = 1
     6         for i in range(1,m+1):
     7             for j in range(1,n+1):
     8                 if not obstacleGrid[i-1][j-1]:
     9                     dp[i][j] = dp[i][j-1] + dp[i-1][j]
    10         return dp[m][n]
    11         

     还有一种占用O(N)空间的方法,感觉挺不错的

    思路:用一个数组tmp记录每一行中每一个位置拥有的次数,每到一个没有障碍物的位置,那么这个位置自动继承上一个位置上所拥有的次数

     1 class Solution(object):
     2     def uniquePathsWithObstacles(self, obstacleGrid):
     3         m,n=len(obstacleGrid),len(obstacleGrid[0])
     4         tmp = [0]*(n+1)
     5         tmp [n-1] = 1
     6         for i in range(m-1,-1,-1):
     7             for j in range(n-1,-1,-1):
     8                 if obstacleGrid[i][j]:
     9                     tmp[j] = 0
    10                 else:
    11                     tmp[j] += tmp [j+1]
    12         return tmp[0]
    13         
  • 相关阅读:
    maven的安装教程
    webstorm的中文教程和技巧分享
    WebStorm
    grunt配置任务
    grunt快速入门
    CSS简介
    浅介HTML DOM
    【转】计算机是如何启动的?
    【转】深入理解C++中public、protected及private用法
    【转】VS2013动态库文件的创建及其使用详解
  • 原文地址:https://www.cnblogs.com/fcyworld/p/6538435.html
Copyright © 2020-2023  润新知