problem:
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.
和前面两题思路一致,分类for循环即可,判断左边和上边哪个小,就加上哪个。
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int test;
vector<vector<int> > result(m, vector<int>(n,0));
result[0][0] = grid[0][0];
for(int i=1; i<m; i++)
{
result[i][0] = result[i-1][0] + grid[i][0];
test = result[i][0];
}
for(int j=1; j<n; j++)
{
result[0][j] = result[0][j-1] + grid[0][j];
test = result[0][j];
}
for(int i=1; i<m; i++)
{
for(int j=1; j<n; j++)
{
int temp = min(result[i-1][j], result[i][j-1]);
result[i][j] = temp + grid[i][j];
test = result[i][j];
}
}
return result[m-1][n-1];
}
};