[LeetCode]63. Unique Paths II
63. Unique Paths II
dp[i][j] = 0 (if arr[i][j] == 1)
dp[i][j] = 1 (if arr[i][j] != 1 and (i == 0 or j == 0))
dp[i][j] = dp[i-1][j] + dp[i][j-1] (if arr[i][j] != 1 and i != 0 and j != 0)动态规划
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
dp = []
row, col = len(obstacleGrid), len(obstacleGrid[0])
for i in range(row):
dp.append([0] * col)
# 第一行
for i in range(row):
if obstacleGrid[i][0] != 1:
dp[i][0] = 1
else:
break
# 第一列
for j in range(col):
if obstacleGrid[0][j] != 1:
dp[0][j] = 1
else:
break
for i in range(1, row):
for j in range(1, col):
if obstacleGrid[i][j] != 1:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
else:
dp[i][j] = 0
return dp[row-1][col-1]
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
if not obstacleGrid or not obstacleGrid[0]:
return 0
row, col = len(obstacleGrid), len(obstacleGrid[0])
dp = [0] * col
for j in xrange(col):
if obstacleGrid[0][j]:
break
dp[j] = 1
for i in xrange(1, row):
for j in xrange(col):
if obstacleGrid[i][j]:
dp[j] = 0
else:
left = dp[j - 1] if j > 0 else 0
dp[j] += left
return dp[col - 1]
关注公众号:数据结构与算法那些事儿,每天一篇数据结构与算法

浙公网安备 33010602011771号