LeetCode刷题笔记--64. Minimum Path Sum

64. Minimum Path Sum

Medium

128437FavoriteShare

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizesthe 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.

解题的思路是:

从右下角开始填,先填最下面一行,再填最右侧一行,最后填中间的格子,格子中的值等于min(格子右边的的值,格子下边的值)+格子本身的值。

AC的答案:

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        if(grid.size()==0)return 0;
        if(grid.size()==1&&grid[0].size()==0)return 0;
        
        int rows=grid.size();
        int cols=grid[0].size();
        
        vector<vector<int>> t(rows,vector<int>(cols,0));
       
        t[rows-1][cols-1]=grid[rows-1][cols-1];
        
        //先填最下面一行
        for(int x=cols-2;x>=0;x--)
        {
            t[rows-1][x]=grid[rows-1][x]+t[rows-1][x+1];
        }
        
        //再填最右边一列
        for(int x=rows-2;x>=0;x--)
        {
            t[x][cols-1]=grid[x][cols-1]+t[x+1][cols-1];
        }
        
        //最后填中间的格子,格子中的值等于min(格子右边的的值,格子下边的值)+格子本身的值
        for(int x=rows-2;x>=0;x--)
        {
            for(int y=cols-2;y>=0;y--)
            {
                t[x][y]=min(t[x+1][y],t[x][y+1])+grid[x][y];
            }
        }
        
        return t[0][0];
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值