本题属于典型的动态规划,以下是解题思路以及Python代码。
1.思路
1)动态规划
因为只能向右或者向下走
[i][j] = min{[i-1][j]+[i][j-1]} + [i][j]
2)滚动求和
目的是节省空间,只需要一个二维数组
基于[0][0],求出第一行和第一列上的每一个值(加上前面一个数字,滚动求和)
再动态规划求出[i][j]
Note:注意行列的index不能超出范围,行列不能混乱
2.代码
class Solution:
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
columns = len(grid[0])
rows = len(grid)
for i in range(1, columns):
grid[0][i] = grid[0][i] + grid[0][i - 1]
for i in range(1, rows):
grid[i][0] = grid[i][0] + grid[i - 1][0]
for i in range(1, rows):
for j in range(1, columns):
grid[i][j] = min(grid[i][j - 1], grid[i -1][j]) + grid[i][j]
return grid[rows - 1][columns - 1]