0. 链接
1. 题目
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:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
2. 思路1:动态规划
image.pngdp[i][j]表示到达(i,j)的最短路径长度, 则
- 初始条件为:
dp[0][0] = grid[0][0]
- 对于
i > 0, j = 0
因为(i, 0)
只能由(i - 1, 0)
向下一步到达, 所以
dp[i][0] = dp[i - 1][0] + grid[i][0]
- 对于
i = 0, j > 0
因为(0, j)
只能由(0, j - 1)
向右一步到达, 所以
dp[0][j] = dp[0][j - 1] + grid[0][j]
- 对于
i > 0 and j > 0
因为(i, j)
只能由(i - 1, j)
向下一步或(i, j - 1)
向右一步到达,所以
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
3. 代码
# coding:utf8
from typing import List
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
m = len(grid)
n = 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] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
return dp[m - 1][n - 1]
solution = Solution()
grid = [
[1,3,1],
[1,5,1],
[4,2,1]
]
print('input={}, output={}'.format(grid, solution.minPathSum(grid)))
输出结果
input=[[1, 3, 1], [1, 5, 1], [4, 2, 1]], output=7
网友评论