美文网首页
64. 最短路径和

64. 最短路径和

作者: 葡萄肉多 | 来源:发表于2019-11-25 21:26 被阅读0次

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.

思路

动态规划,设置dp数组,dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
首先先计算第一行和第一列的dp值,因为只有唯一路径,再计算其他位置。

class Solution:
    def minPathSum(self, grid) -> 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, n):
            dp[0][i] = dp[0][i-1] + grid[0][i]
        for i in range(1, m):
            dp[i][0] = dp[i-1][0] + grid[i][0]
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + grid[i][j]
        print(dp)
        return dp[m-1][n-1]

相关文章

网友评论

      本文标题:64. 最短路径和

      本文链接:https://www.haomeiwen.com/subject/lccswctx.html