题目描述:
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.
给定一个m*n的矩形a, 计算从a[0][0]到a[m][n]的每个数字加起来最小的和. 注意, 每次只能往下或者右查找下一个数字.
分析:
每次都往右下角寻找. 之前看到一道题, 计算n*n的方形从左上角到又下角最短的距离有多少种走法. 我们先来看这个问题.
假设在4*4的格子中, a[i][j] 的值 等于a[i-1][j] + a[j-1][i], 如下图所示:
1 1 1 1
1 2 3 4
1 3 6 10
1 4 10 20
上面展示的是的最短路径有多少种走法.
然后在计算从左上角到右下角最小数字和时,采用动态规划的思想, 每一步的最小取值,依赖其左边和上边的最小值,
我们设m[i][j] 是走到第a[i][j]时,最小的元素和, 由上面可以得出,
m[i][j] = min(m[i-1][j]+a[i][j], m[i][j-1]+a[i][j])
其中: m[i][0] = a[i][0] m[0][j] = a[0][j]
代码如下:
1 class Solution(object): 2 def minPathSum(self, grid): 3 """ 4 :type grid: List[List[int]] 5 :rtype: int 6 """ 7 n = len(grid) 8 if n == 0: 9 return 0 10 m = len(grid[0]) 11 a = [[0 for i in range(m)]for j in range(n)] 12 a[0][0] = grid[0][0] 13 for j in range(1, m): 14 a[0][j] = a[0][j-1] + grid[0][j] 15 for i in range(1, n): 16 a[i][0] = a[i-1][0] + grid[i][0] 17 for i in range (1, n): 18 for j in range(1, m): 19 a[i][j] = min(a[i-1][j]+grid[i][j], a[i][j-1]+grid[i][j]) 20 return a[n-1][m-1]