问题描述:
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.
题源:here;完整实现:here
思路:
使用和第63题,第62题相同的动态规划策略,但需要选择累加更小的路径,代码如下:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size();
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
if (i == 0 && j>0) grid[i][j] += grid[i][j-1];
else if (i > 0 && j == 0) grid[i][j] += grid[i - 1][j];
else if (i > 0 && j > 0) grid[i][j] += min(grid[i - 1][j], grid[i][j - 1]);
}
}
return grid[m - 1][n - 1];}};
贴出运行结果纪念一下: