LeetCode题解:Minimum Path Sum

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.

思路:

一个简单的动态规划问题。位于(y, x)的最小路径和等于(y,x)点处的值加上(y-1, x)点或(y, x-1)点二者之间较小的那个值。填充一个m x n的表格即可得到解。

题解:

class Solution {
public:
    int minPathSum(vector<vector<int> > &grid) {
        if (grid.size() == 0 || grid[0].size() == 0)
            return 0;
    
        const size_t Y = grid.size();
        const size_t X = grid[0].size();
    
        // create the accumulative map
        vector<vector<int>> pathSum(Y);
        for(auto& v : pathSum)
            v.resize(X);
    
        // initialize the trigger
        pathSum[0][0] = grid[0][0];
    
        // such loop is not good
        // since it does not exploit the cache 
        // but let it so
        for(size_t x = 0; x < X; ++x)
            for(size_t y = 0; y < Y; ++y)
            {
                if (x == 0 && y == 0)
                    continue;
                    
                int left = (x == 0 ? INT_MAX : pathSum[y][x - 1]);
                int top =  (y == 0 ? INT_MAX : pathSum[y - 1][x]);
    
                pathSum[y][x] = min(left, top) + grid[y][x];
            }
    
        return pathSum[Y - 1][X - 1];
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值