leetcode 64. Minimum Path Sum
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.
Accepted
Solution
在每一个位置[i][j],要么从上面一个位置下来,要么从左边一个位置过来
所以其动态规划的状态转移方程为
dp[i][j]=min{dp[i-1][j],dp[i][j-1]} + nowLocation
注意第一行和第一列的初始化
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid[0].size();
int n = grid.size();
int dp[n + 1][m + 1];
for (int i = 0; i <= m; i++)
dp[0][i] = 0;
for (int i = 0; i <= n; i++)
dp[i][0] = 0;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
if (i == 1)
dp[i][j] = dp[i][j - 1] + grid[i - 1][j - 1];
else if (j == 1)
dp[i][j] = dp[i - 1][j] + grid[i - 1][j - 1];
else {
dp[i][j] = (dp[i - 1][j] <= dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1]) + grid[i - 1][j - 1];
}
}
return dp[n][m];
}
};