问题描述
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.
解题思路
根据题目描述,每次只能向右或者向下走,因此走到(x, y)时的最小花费,只需要讨论它的左边的最小花费和它的上方的最小花费。也就是说,只需要讨论:
dp(x, y)代表在走到位置(x,y)所需要的最小花费,M(x,y)代表到达这个点需要的花费。
dp(x, y) = min(dp(x - 1, y) + M(x, y), dp(x, y - 1) + M(x, y))
得出上述的状态转移方程之后,我们还需要讨论循环遍历的顺序。按照上述公式,我们在计算(x,y)时必须算出它左边的点以及上一行相同列数的点。要满足这个条件只需要按照行和列的顺序遍历即可。
时间复杂度
遍历一遍所有节点即可,O(m*n)
空间复杂度
和地图一样的大小,O(m*n)
源码
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
int dp[rows][cols];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
dp[i][j] = 0;
}
}
dp[0][0] = grid[0][0];
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (i == 0 && j == 0) {
continue;
} else if (i == 0) {
dp[i][j] = dp[i][j - 1] + grid[i][j];
} else if (j == 0) {
dp[i][j] = dp[i - 1][j] + grid[i][j];
} else {
dp[i][j] = min(dp[i - 1][j] + grid[i][j], dp[i][j - 1] + grid[i][j]);
}
}
}
return dp[rows - 1][cols - 1];
}
};