title
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.
solution
DP,dp[i]表示在i列的路径和
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if (grid.size() == 0 || grid[0].size() == 0) {
return 0;
}
int *dp = new int[grid[0].size()];
fill(dp, dp + grid[0].size(), 0);
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (i == 0) {
dp[j] = dp[j - 1];
}
else if (j == 0) {
dp[j] = dp[j];
}
else {
dp[j] = min(dp[j], dp[j - 1]);
}
dp[j] += grid[i][j];
}
}
return dp[grid[0].size() - 1];
}
};