问题描述:
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:
代码语言:javascript复制Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
解题思路:
很明显使用动态规划求解。创建 dp[m][n],其中 dp[i][j] 表示位置 (i, j) 的最小累加和。最后 dp[-1][-1] 就是答案。
转移方程也很简单:
dp[i][j] = grid[i][j] min(dp[i][j-1], dp[i-1][j])
注意:编程时,需要初始化第一行和第一列。后一个数由前面的数累加得到的,即:
- 左上角元素:
dp[0][0] = grid[0][0]
- 第一列初始化:
dp[i][0] = dp[i-1][0] grid[i][0]
- 第一行初始化:
dp[0][j] = dp[0][j-1] grid[0][j]
Python3 实现:
代码语言:javascript复制class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
dp = [[0] * 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 j in range(1, n):
dp[0][j] = dp[0][j-1] grid[0][j]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = grid[i][j] min(dp[i][j-1], dp[i-1][j])
return dp[-1][-1]
print(Solution().minPathSum([[1,3,1],[1,5,1],[4,2,1]])) # 7 (1->3->1->1->1)