【Leetcode】【python】Minimum Path Sum

题目大意

从一个矩阵的左上角出发到右下角,只能向右或向下走,找出哪一条路径上的数字之和最小。

注意点:

所有数字都是非负的

解题思路

动态规划,承接http://blog.csdn.net/qqxx6661/article/details/78231730
不过从计算到达该点有多少种走法转变为求最小和为多少。找出上面和左边格子的最小值加上当前格子中的数字即可。

1
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
m = len(grid)
n = len(grid[0])
dp = [[0 for __ in range(n)] for __ in range(m)]
dp[0][0] = grid[0][0]
for i in range(1, m):
dp[i][0] = dp[i-1][0] + grid[i][0]
for i in range(1, n):
dp[0][i] = dp[0][i-1] + grid[0][i]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = min(dp[i-1][j] + grid[i][j], dp[i][j-1] + grid[i][j])
return dp[-1][-1]

总结