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 1:
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
The total number of unique paths is 2.
题意是: 给一个m*n的矩阵,矩阵的值表示通过该位置所需要的权重,求道点[m,n]所耗费最小的权重。
其实这道题还是跟leetcode 62 和 leetcode 63有点类似,唯一不同的是推导公式不再是路径数,而是[i-1,j]和[i,j]的权重的最小值加上该位置的权重,因此需要进行一个判断,P[i,j]=G[i,j]+min(P[i-1,j]+P[i,j-1]),只需要选择最小的那个路径权重。
当j=0的时候,路径只能是从上边下来,所以直接P[i,0]=P[i-1,0]。
代码:
int minPathSum(vector<vector<int>> &grid)
{
int re=0;
if(grid.size()==0)
{
return re;
}
vector<int> path(grid[0].size(),0);
for(int i=0;i<grid.size();i++)
{
path[0]+=grid[i][0];
for(int j=1;j<grid[i].size();j++)
{
if(i==0)
{
path[j]=path[j-1]+grid[i][j];
}
else
{
if(path[j-1]<path[j])
path[j]=grid[i][j]+path[j-1];
else
path[j]=grid[i][j]+path[j];
}
}
}
re=path[path.size()-1];
return re;
}