美文网首页
64. Minimum Path Sum/最小路径和

64. Minimum Path Sum/最小路径和

作者: 蜜糖_7474 | 来源:发表于2019-06-01 10:38 被阅读0次

    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:

    Input:
    [
    [1,3,1],
    [1,5,1],
    [4,2,1]
    ]
    Output: 7
    Explanation: Because the path 1→3→1→1→1 minimizes the sum.

    AC代码

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

    总结

    动态规划的思想与上题一致,将int改为short可减少内存占用

    相关文章

      网友评论

          本文标题:64. Minimum Path Sum/最小路径和

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