64. Minimum Path Sum
Medium
128437FavoriteShare
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizesthe 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.
解题的思路是:
从右下角开始填,先填最下面一行,再填最右侧一行,最后填中间的格子,格子中的值等于min(格子右边的的值,格子下边的值)+格子本身的值。
AC的答案:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size()==0)return 0;
if(grid.size()==1&&grid[0].size()==0)return 0;
int rows=grid.size();
int cols=grid[0].size();
vector<vector<int>> t(rows,vector<int>(cols,0));
t[rows-1][cols-1]=grid[rows-1][cols-1];
//先填最下面一行
for(int x=cols-2;x>=0;x--)
{
t[rows-1][x]=grid[rows-1][x]+t[rows-1][x+1];
}
//再填最右边一列
for(int x=rows-2;x>=0;x--)
{
t[x][cols-1]=grid[x][cols-1]+t[x+1][cols-1];
}
//最后填中间的格子,格子中的值等于min(格子右边的的值,格子下边的值)+格子本身的值
for(int x=rows-2;x>=0;x--)
{
for(int y=cols-2;y>=0;y--)
{
t[x][y]=min(t[x+1][y],t[x][y+1])+grid[x][y];
}
}
return t[0][0];
}
};