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.
思路:用一个数组存从起点到终点的最短距离。初始化时,全体初始化为最大整数。按行遍历grid,sum就记录从起点到当前行对应sum的列的路径和,每次sum的值取当前值与前一步路径和的较小值+当前格子的值。sum的最后记录的就是从左上起点到右下终点的最短距离。
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> sum(grid[0].size()+1, INT_MAX);
sum[1] = 0;
for(int i=0; i<grid.size(); i++){
for(int j=1; j<=grid[0].size(); j++){
sum[j] = min(sum[j-1], sum[j]) + grid[i][j-1];
}
}
return sum.back();
}
};