Question:
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.
Solution:
用动态规划,思路和做过的174. Dungeon Game是一样的,而且没那题那么复杂要考虑几种情况。
从最右下方开始往回遍历,状态转移方程为:
f(i, j) = min(f(i, j+1), f(i+1, j)) + nums(i, j)
即每次只可以去右边或者下边,选最小的那个走就行了。初始化时f(m, n) = nums(m, n)
并且注意边界的情况就好。
和174那题一样,空间上可以只用一维数组,可以用f(j+1)
代替 f(i, j+1)
因为f(j+1)
是最新更新的,用f(j)
代替f(i+1, j)
因为f(j)
是之前 (i-1)
那一层的。
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if (grid.size() == 0)
return 0;
int m = grid.size(), n = grid[0].size();
vector<int> dp(n, 0);
dp[n-1] = grid[m-1][n-1];
for (int j = n-2; j >= 0; j--)
dp[j] = dp[j+1] + grid[m-1][j];
for (int i = m-2; i >= 0; i--) {
dp[n-1] += grid[i][n-1];
for (int j = n-2; j >= 0; j--) {
dp[j] = min(dp[j+1], dp[j]) + grid[i][j];
}
}
return dp[0];
}
};