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.
Example:
Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum.
给定一个m×n的网格,其中填充了非负数,请找到一条从左上到右下的路径,该路径将沿其路径的所有数字的总和最小化。
注意:您只能在任何时间点向下或向右移动。
依然是动态规划的问题,使用贪心算法就落入了出题者的陷阱。
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
// check size
int m = grid.size();
if(!m)
return 0;
int n = grid.at(0).size();
if(!n)
return 0;
// initailize
vector<int> buffer(n, 0);
vector<vector<int>> result(m, buffer);
// calculate
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(i > 0 && j > 0){
result.at(i).at(j) = grid.at(i).at(j) + min(result.at(i-1).at(j), result.at(i).at(j-1));
}
else if(i > 0){
result.at(i).at(j) = grid.at(i).at(j) + result.at(i-1).at(j);
}
else if(j > 0){
result.at(i).at(j) = grid.at(i).at(j) + result.at(i).at(j-1);
}
else{
result.at(i).at(j) = grid.at(i).at(j);
}
}
}
return result.at(m-1).at(n-1);
}
};