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.
解题技巧:
该题的解法类似于Unique Paths、Unique PathsII,采用动态规划的方法,不过,该题求从起点到终点的最短路径长度。
状态转换方程为:step[i][j] = min(step[i-1][j] , step[i][j-1]) + grid[i][j]
代码:
int minPathSum(vector< vector<int> >& grid)
{
int m = grid.size(), n = grid[0].size();
vector< vector<int> > step(m, vector<int>(n, 0));
for(int i = 0; i < m; i ++)
{
for(int j = 0 ; j < n; j ++)
{
if(i == 0 && j == 0)
{
step[i][j] = grid[i][j];
}
else if(i == 0)
{
step[i][j] = step[i][j-1] + grid[i][j];
}
else if(j == 0)
{
step[i][j] = step[i-1][j] + grid[i][j];
}
else
{
if(step[i-1][j] < step[i][j-1])
step[i][j] = step[i-1][j] + grid[i][j];
else
step[i][j] = step[i][j-1] + grid[i][j];
}
}
}
return step[m-1][n-1];
}