LeetCode 64. Minimum Path Sum 动态规划

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.

题意

给定一个mxn的栅格,里边都是正整数。找到一条最小路径和从左上角到右下角。

思路

和120. Triangle思路2类似。自顶向下

  • mingridPath[k][i] = min(mingridPath[k-1][i],mingridPath[k][i-1])+grid[k][i]

一行一行的扫描,从左到右,从上到下
注意:第一行没有上边的元素,其最小路径和都是左边元素相加
第一列没有左侧元素,其最小路径和都是上边的元素相加

代码

class Solution {
public:
    int minPathSum(vector<vector<int>>& grid) {
        for(int i=0;i<grid.size();i++)
        {
            int top = 999999;
            int left = 999999;
            for(int j=0;j<grid[i].size();j++)
            {
                if(i == 0&&j==0)
                    continue;
                if(i>0)  //第一行元素没有上边的元素
                    top = grid[i-1][j];
                if(j>0)  //第一列没有左侧的元素
                    left = grid[i][j-1];
                grid[i][j] = grid[i][j]+min(left,top);
            }
        }        
        return grid.back().back();
    }
};

你可能感兴趣的:(LeetCode,动态规划)