Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right whichminimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
题意:给定m*n矩阵,里面都是非负数,求从左上角,走到右下角的路径,要求这条路径过程中所有数加起来的和最小
分类:数组,动态规划
动态规划:
MPS[i][j] = Min(MPS[i-1][j],MPS[i][j-1])+ val[i][j];
边界处理条件:
for(int j=1; j<res[0].size(); ++j){
res[0][j] += res[0][j-1];
}
for(int j=1; j<res.size(); ++j){
res[j][0] += res[j-1][0];
}
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if(grid.size()==0)
return 0;
vector<vector<int>> res(grid);
int i, j;
for(int j=1; j<res[0].size(); ++j){
res[0][j] += res[0][j-1];
}
for(int j=1; j<res.size(); ++j){
res[j][0] += res[j-1][0];
}
for(i=1; i<res.size(); ++i){
for(int j=1; j<res[i].size(); ++j){
res[i][j] = min(res[i-1][j], res[i][j-1])+grid[i][j];
}
}
return res[grid.size()-1][grid[0].size()-1]; //注意行列的size不一定一样
}
};