题目描述(Medium)
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.
题目链接
https://leetcode.com/problems/minimum-path-sum/description/
Example 1:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
算法分析
对每一行有路径转移方程path[j] = min(path[j], path[j - 1]) + grid[i][j],path[j]代表当前行每一列的最小到达路径。
提交代码:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
const int m = grid.size();
const int n = grid[0].size();
vector<int> path(n, INT_MAX);
path[0] = 0;
for (int i = 0; i < m; ++i) {
path[0] += grid[i][0];
for (int j = 1; j < n; ++j) {
path[j] = min(path[j], path[j - 1]) + grid[i][j];
}
}
return path[n - 1];
}
};