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.
1:特殊情况的考虑;2:设置一个n大小的数组。3:遍历二维数组,在遍历的过程中计算每一个位置上的最小值
int minPathSum(vector<vector<int> > &grid) {
if(grid.size() == 0 || grid[0].size() == 0)
return 0;
int rows = (int)grid.size();
int columns = (int)grid[0].size();
vector<int> path(columns, 0);
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
if(i == 0 && j == 0)
{
path[j] = grid[i][j];
}
else if(i == 0)
{
path[j] = path[j-1] + grid[i][j];
}
else if(j == 0)
{
path[0] = path[0] + grid[i][j];
}
else
{
path[j] = (path[j-1] < path[j] ? path[j-1] : path[j]) + grid[i][j];
}
}
}
return path[columns - 1];
}