[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