LeetCode #64 Minimum Path Sum
题目
解题方法
这是一道动态规划题,与Unique Paths类似,区别在于此题要选择每个格点上方和左方中的最小值与该格点的值相加,作为到达该格点所需要的最小值,循环做到终点就可以得到最终答案。
代码
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
for i in range(1, len(grid)):
grid[i][0] += grid[i-1][0]
for i in range(1, len(grid[0])):
grid[0][i] += grid[0][i-1]
for i in range(1, len(grid)):
for j in range(1, len(grid[0])):
grid[i][j] += min(grid[i-1][j], grid[i][j-1])
return grid[-1][-1]