-题目-
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 Path的题目的思路来解,以二维数组记录到达每一个点所需要的最短路径长度,则状态转移方程就是f[i][j]=min(f[i-1][j], f[i][j-1])+grid[i][j].最后的结果存储在f[n-1][n-1]中。相较于之前的path这道题难度在于第一和第一行的初始化,感觉用现在的代码初始化很大程度上拉低了效率,因此这道题目前的答案其实还需要改进。
-代码-
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size() == 0) return 0;
vector<vector<int> > min_path(grid.size());
for(int i = 0; i < grid.size(); i++) {
min_path[i].resize(grid[i].size(), 0);
}
min_path[0][0] = grid[0][0];
for(int i = 1; i < grid.size(); i++) {
for(int j = 0; j <= i; j++)
min_path[i][0] += grid[j][0];
}
for(int i = 1; i < grid[0].size(); i++) {
for(int j = 0; j <= i; j++) {
min_path[0][i] += grid[0][j];
}
}
for(int i = 1; i < grid.size(); i++) {
for(int j = 1; j < grid[i].size(); j++) {
min_path[i][j] = min(min_path[i][j-1], min_path[i-1][j])+grid[i][j];
}
}
return min_path[grid.size()-1][grid[0].size()-1];
}
};