题目描述:
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
.
Note: m and n will be at most 100.
这道题是之前的变体,我想了好一会儿没想出来,因为陷入了一个误区。我想,当遍历的时候碰到1就应该转变方向了,比如当nums[i][j]=1时,应该有一个i-1,j+1的操作回退,似于回溯的思想。但是不是,不需要那么思考。class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
m = len(obstacleGrid)
n = len(obstacleGrid[0])
a = [([0] * (n+1)) for i in range(m+1)]
if obstacleGrid[0][0] == 1:
return 0
else:
a[0][1] = 1
for i in range(0,m):
for j in range(0,n):
if obstacleGrid[i][j] == 0:
a[i+1][j+1] = a[i][j+1] + a[i+1][j]
return a[m][n]
其实也没什么好解释的。