64. Minimum Path Sum

Description:

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 1:

[[1,3,1],
 [1,5,1],
 [4,2,1]]
Given the above grid map, return  7. Because the path 1→3→1→1→1 minimizes the sum.

简要题解:

采用动态规划。

子问题c(i, j): 表示以grid[0][0]为起点,grid[i][j]为终点的最小路径和。

第一个子问题c(0, 0) = grid[0][0]。

子问题c(i , j)与前面的子问题的一般关系:c(i, j) = min(c(i - 1, j), c(i, j - 1)) + grid[i][j]。


代码:

class Solution {
public:
    int minPathSum(vector<vector<int> >& grid) {
        int m = grid.size();
        if (0 == m)
            return 0;
        int n = grid[0].size();
        if (0 == n)
            return 0;
        
         vector<vector<int> > dp(m, vector<int>(n, 0));
        
        int cost;
         for (int i = 0; i < m; i++)
            for (int j = 0; j < n; j++) {
                cost = 0;
                if (i - 1 >= 0)
                    cost = dp[i-1][j];
                if (j - 1 >= 0 && 0 == cost)
                    cost = dp[i][j-1];
                else if (j - 1 >= 0)
                    cost = (cost > dp[i][j-1]) ? dp[i][j-1] : cost; 
                
                dp[i][j] = cost + grid[i][j];
            }
        
        return dp[m-1][n-1];
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值