Description:
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.
采用动态规划。
子问题c(i, j): 表示以grid[0][0]为起点,grid[i][j]为终点的最小路径和。
第一个子问题c(0, 0) = grid[0][0]。
子问题c(i , j)与前面的子问题的一般关系:c(i, j) = min(c(i - 1, j), c(i, j - 1)) + grid[i][j]。
代码:
class Solution {
public:
int minPathSum(vector<vector<int> >& grid) {
int m = grid.size();
if (0 == m)
return 0;
int n = grid[0].size();
if (0 == n)
return 0;
vector<vector<int> > dp(m, vector<int>(n, 0));
int cost;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
cost = 0;
if (i - 1 >= 0)
cost = dp[i-1][j];
if (j - 1 >= 0 && 0 == cost)
cost = dp[i][j-1];
else if (j - 1 >= 0)
cost = (cost > dp[i][j-1]) ? dp[i][j-1] : cost;
dp[i][j] = cost + grid[i][j];
}
return dp[m-1][n-1];
}
};