[leetcode-64-Minimum Path Sum]

Posted hellowOOOrld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode-64-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.

思路:

很典型的DP问题,如果用grid保存路径和的话

很明显grid[i][j] = grid[i][j] + min(grid[i - 1][j], grid[i][j - 1]);

    int minPathSum2(vector<vector<int>>& grid)
    {
        if (grid.empty())return 0;
        int row = grid.size();
        int col = grid[0].size();
        //其实可以不必申请空间 直接使用grid就行        
        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                if (i==0 && j!=0)
                {
                    grid[i][j] += grid[i][j - 1];
                }
                if (i != 0 && j == 0)
                {
                    grid[i][j] += grid[i - 1][j];
                }
                if (i!=0&&j!=0)
                {
                    grid[i][j] = grid[i][j] + min(grid[i - 1][j], grid[i][j - 1]);
                }                
            }
        }
        return grid[row - 1][col - 1];
    }

 



以上是关于[leetcode-64-Minimum Path Sum]的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode64 Minimum Path Sum

[leetcode-64-Minimum Path Sum]

LeetCode 64. Minimum Path Sum

leetcode 64. Minimum Path Sum

LeetCode64 Minimum Path Sum

LeetCode-64-Minimum Path Sum