[LeetCode] 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.

这道题跟之前那道 Dungeon Game 地牢游戏 没有什么太大的区别,都需要用动态规划Dynamic Programming来做,这应该算是DP问题中比较简单的一类,我们维护一个二维的dp数组,其中dp[i][j]表示当前位置的最小路径和,递推式也容易写出来 dp[i][j] = grid[i][j] + min(dp[i - 1][j], 反正难度不算大,代码如下:

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

本文转自博客园Grandyang的博客,原文链接:最小路径和[LeetCode] Minimum Path Sum ,如需转载请自行联系原博主。

相关文章
|
3月前
代码随想录Day33 LeetCode T62不同路径 LeetCode T63 不同路径II
代码随想录Day33 LeetCode T62不同路径 LeetCode T63 不同路径II
47 0
|
1月前
leetcode热题100.二叉树中的最大路径和
leetcode热题100.二叉树中的最大路径和
18 0
|
1月前
|
vr&ar
leetcode热题100.路径总和 III
leetcode热题100.路径总和 III
19 1
力扣1496 判断路径是否相交
力扣1496 判断路径是否相交
|
2月前
LeetCode题:931下降路径最小和
LeetCode题:931下降路径最小和
26 0
|
28天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
1月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
1月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
143 38