分四种情况:
两条边界和不在边界的情况,因为是在原数组上修改,所以都等于0时不需要改变
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
for i in range(len(grid)):
for j in range(len(grid[0])):
if i == j == 0: continue
elif i == 0: grid[i][j] = grid[i][j - 1] + grid[i][j]
elif j == 0: grid[i][j] = grid[i - 1][j] + grid[i][j]
else: grid[i][j] = min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j]
return grid[i][j]
递归实现
还是分为几种情况,用备忘录记住已经计算过的路径长度,出界返回一个大值,到达返回当前格子的大小
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
memo = [[-1]*n for i in range(m)]
def dp(grid,m,n):
if m == 0 and n == 0:
return grid[m][n]
if m < 0 or n < 0:
return 0x3f3f3f3f
if memo[m][n] != -1:
return memo[m][n]
memo[m][n] = min(dp(grid,m-1,n),dp(grid,m,n-1)) + grid[m][n]
return memo[m][n]
return dp(grid,m-1,n-1)