LeetCode 64. 最小路径和
解题思路:属于坐标行动态规划。首先开一个二维的数组dp[m][n],dp[i][j]代表到第i行第j列为止的最小路径和。每个位置最小的路径和依赖于它的上一行和它的前一列,所以状态转移方程:dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
代码实现:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
//初始化
vector<vector<int>> dp(m, vector<int>(n, 0));
//边界,第一行和第一列
dp[0][0] = grid[0][0];
for (int j = 1; j < n; ++j) dp[0][j] = dp[0][j - 1] + grid[0][j];//第一行
for (int i = 1; i < m; ++i) dp[i][0] = dp[i - 1][0] + grid[i][0];//第一列
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[m - 1][n - 1];
}
};