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 1:
[[1,3,1], [1,5,1], [4,2,1]]
Given the above grid map, return 7
.
Because the path 1→3→1→1→1 minimizes the sum.
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
int sum[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
sum[i][j] = 0;
}
}
sum[0][0] = grid[0][0];
for(int i=1;i<m;i++)
sum[i][0] = grid[i][0] + sum[i-1][0];
for(int j=1;j<n;j++)
sum[0][j] = grid[0][j] + sum[0][j-1];
for(int i=1;i<m;i++)
{
for(int j=1;j<n;j++)
{
if(sum[i][j-1] > sum[i-1][j])
sum[i][j] = sum[i-1][j] + grid[i][j];
else
sum[i][j] = sum[i][j-1] + grid[i][j];
}
}
return sum[m-1][n-1];
}
};
没什么好说的,基础题目