62.不同路径
视频讲解:动态规划中如何初始化很重要!| LeetCode:62.不同路径_哔哩哔哩_bilibili
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
#set dp for m*n table
dp= [[1]*n]*m
#go from the index 1 of column and row because there is only one way to
#reach the first row and the first column location .
for i in range(1,m):
for j in range(1,n):
#only can reach to current point from top and left
dp[i][j]=dp[i-1][j]+dp[i][j-1]
#return the last location number.
return dp[-1][-1]
63. 不同路径 II
视频讲解:动态规划,这次遇到障碍了| LeetCode:63. 不同路径 II_哔哩哔哩_bilibili
class Solution(object):
def uniquePathsWithObstacles(self, obstacleGrid):
"""
:type obstacleGrid: List[List[int]]
:rtype: int
"""
#set up a dp table
row = len(obstacleGrid)
col = len(obstacleGrid[0])
dp = [[0 for _ in range(col)] for _ in range(row)]
#set base number as 1 unless the corresponding dp is 0
dp[0][0] = 0 if obstacleGrid[0][0] == 1 else 1
#return 0 if the start is 0
if dp[0][0] == 0:
return 0
# for the first row, if the current location is 1, go to a break, which
#means the grid after the cur cannot be reached
for i in range(1, col):
if obstacleGrid[0][i] == 1:
break
dp[0][i] = 1
# for the first col, do the same thing as pricessing the row
for i in range(1, row):
if obstacleGrid[i][0] == 1:
break
dp[i][0] = 1
#for dp[i][j],we add the value from top and left to get the different
#ways to reach cur
for i in range(1, row):
for j in range(1, col):
if obstacleGrid[i][j] == 0:
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
#return the result
return dp[-1][-1]