LeetCode:64. Minimum Path Sum

博客围绕LeetCode 64题最小路径和展开,该题是62题每个格子加权重后的考法,目标是求从左上角到右下角使走过格子权重之和最小的走法。采用动态规划思路,给出状态转移方程,同时要注意第一行和第一列的特殊情况,还提及用Python代码实现。

LeetCode:64. Minimum Path Sum

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.

这题就是62. Unique Paths每一个格子加上权重之后的考法,就是求左上角到右下角那种走法使得走过的格子权重之和最小。

思路:动态规划

设要求到达(i,j)处格子的路径最小权重之和为res(i,j),且(i,j)处的权重为grid(i,j),那么:

res(i,j) = min(res(i-1,j),res(i,j-1))+grid(i,j)

同时注意下第一行和第一列两种特殊情况即可。

Python代码实现

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        m=len(grid)
        n=len(grid[0])
        ans=0
        res={}
        if m==1 and n==1:
            ans=grid[0][0]
        else:
            
            for i in range(m):
                for j in range(n):
                    if i==0 and j==0:
                        res[(i,j)]=grid[i][j]
                    elif i==0:
                        res[(i,j)]=res[(i,j-1)]+grid[i][j]
                    elif j==0:
                        res[(i,j)]=res[(i-1,j)]+grid[i][j]
                    else:
                        res[(i,j)]=min(res[(i-1,j)],res[i,j-1])+grid[i][j]
            ans=res[(i,j)]
        return ans

THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值