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.
class Solution {
public:int minPathSum(vector<vector<int> > &grid) {
int rows = grid.size();
int cols = grid[0].size();
vector<int> temp(cols, 0);
vector<vector<int> > dp(rows, temp);
dp[0][0] = grid[0][0];
for (int i=1;i<rows;i++)
dp[i][0] = grid[i][0] + dp[i-1][0];
for (int j=1;j<cols;j++)
dp[0][j] = grid[0][j] + dp[0][j-1];
for (int i=1;i<rows;i++){
for (int j=1;j<cols;j++){
dp[i][j] = min(dp[i-1][j] + grid[i][j],
dp[i][j-1] + grid[i][j]);
}
}
return dp[rows-1][cols-1];
}
};