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 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.
这道题与之前的 Unique Path 和 Unique Path 两道题类似,在这道题的情形下不再是求左上角到达右下角方格的路径数量,而是求到达右下角方格的最短距离。矩阵的值可以理解为到达方格所需要的代价,我们需要做的就是找到一条代价最小的到达右下角的路径并求出这个最短距离。
与Unique Path 相同,我们依然只能向右方和左方移动,每一个方格的前一个方格都只能是它左边或上边的方格,则到达每个方格的代价等于到达它左边或上边方格的代价加上到达它自己的代价,又因为我们要求的是最小的代价,因此我们需要在左边方格和上边方格中选择代价较少的那一个。由上我们可以得到
grid[ i ][ j ] = min(grid[ i - 1 ][ j ], grid[ i ][ j - 1 ]) + grid[ i ][ j ];
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i - 1 >= 0 && j - 1 >= 0) {
grid[i][j] = min(grid[i - 1][j], grid[i][j - 1]) + grid[i][j];
} else if (i - 1 >= 0) {
grid[i][j] = grid[i - 1][j] + grid[i][j];
} else if (j - 1 >= 0) {
grid[i][j] = grid[i][j - 1] + grid[i][j];
}
}
}
return grid[m - 1][n - 1];
}
};