题目描述:
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example 1:
[[1,3,1], [1,5,1], [4,2,1]]Given the above grid map, return
7
. Because the path 1→3→1→1→1 minimizes the sum.
跟之前的题的思路都差不多。
class Solution:
def minPathSum(self, grid):
m = len(grid)
n = len(grid[0])
a = grid
for i in range(1,n):
a[0][i] +=a[0][i-1]
for j in range(1,m):
a[j][0] +=a[j-1][0]
for i in range(1,m):
for j in range(1,n):
a[i][j]+= min(a[i][j-1],a[i-1][j])
return a[m-1][n-1]
grid[0][i],和grid[j][0]都是只有一条路径可以走的,所以可以作为预处理的一部分。