美文网首页
64.最小路径

64.最小路径

作者: HITZGD | 来源:发表于2018-11-17 21:12 被阅读0次

题目
给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。

说明:每次只能向下或者向右移动一步。

示例:

输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。

思路
方法类同62和63,但是在求path[i][j]时需要加的时其本身和左上的最小值

#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        int sizeOf = grid.size(), lengthOf = grid[0].size();
        vector<vector<int>>path(sizeOf, vector<int>(lengthOf, 0));
        path[0][0] = grid[0][0];
        for (int i = 1; i < sizeOf; ++i)
        {
            path[i][0] = grid[i][0] + path[i - 1][0];
        }
        for (int i = 1; i < lengthOf; ++i)
        {
            path[0][i] = grid[0][i] + path[0][i - 1];
        }
        for (int i = 1; i < sizeOf; ++i)
            for (int j = 1; j < lengthOf; ++j)
            {
                path[i][j] = grid[i][j] + min(path[i - 1][j], path[i][j - 1]);
            }
        return path[sizeOf - 1][lengthOf - 1] ;
    }
};

int main(int argc, char* argv[])
{
    vector<vector<int>> test = { { 1,3,1 },{ 1,5,1 },{ 4,2,1 } };
    auto res = Solution().minPathSum(test);
    return 0;
}

相关文章

  • 【D13】最小路径和 & 爬楼梯 (LC 64&70)

    64. 最小路径和[https://leetcode-cn.com/problems/minimum-path-s...

  • LeetCode 64. 最小路径和 | Python

    64. 最小路径和 题目来源:力扣(LeetCode)https://leetcode-cn.com/proble...

  • 64.最小路径

    题目给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明...

  • 64.最小路径和

    链接: 64.最小路径和 思路: dp[i][j]=min(dp[i-1][j],dp[i][j-1])+grid...

  • 64.最小路径和

  • 64. 最小路径和

    题目 给定一个只含非负整数的 m x n 网格,找到一条从左上角到右下角的可以使数字之和最小的路径。 注意: 每次...

  • 64. 最小路径和

    1. 题目 给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最...

  • 64. 最小路径和

    解题思路 思路:从右下往左上找,用dp数组来保存右下元素到括号指定点的距离遍历整个矩阵,分四种情况:1:仅仅代表最...

  • 64. 最小路径和

  • 64. 最小路径和

    给定一个包含非负整数的 m x n 网格,请找出一条从左上角到右下角的路径,使得路径上的数字总和为最小。 说明:每...

网友评论

      本文标题:64.最小路径

      本文链接:https://www.haomeiwen.com/subject/fpwifqtx.html