这个题是力扣62不同路径的改进,在路径上多了障碍物需要思考。
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
# 有障碍物,那么有障碍物的位置路径=0
# 1.dp
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0 for i in range(n)] for j in range(m)]
# 先对第一个点做个判断
if obstacleGrid[0][0] == 1:
return 0
# 初始化
for i in range(m):
# 只有无障碍的位置,才可以赋初值=1,如果有障碍,那么这一列后面的值都为0
if obstacleGrid[i][0] == 0:
dp[i][0] = 1
else:
break
for j in range(n):
# 只有无障碍的位置,才可以赋初值=1,如果有障碍,那么这一行后面的值都为0
if obstacleGrid[0][j] == 0:
dp[0][j] = 1
else:
break
for i in range(1, m):
for j in range(1, n):
if obstacleGrid[i][j] != 1:
dp[i][j] = dp[i][j-1] + dp[i-1][j]
return dp[-1][-1]
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
# 2.方法1的优化,空间复杂度为O(n)
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [0 for _ in range(n)]
if obstacleGrid[0][0] == 1:
return 0
for i in range(n):
if obstacleGrid[0][i] == 1:
break
dp[i] = 1
for i in range(1, m):
for j in range(n):
if obstacleGrid[i][j] == 1:
dp[j] = 0
elif j > 0:
dp[j] += dp[j-1]
return dp[-1]