题目:
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.
描述:
给出一个矩阵,问从左上角到右下角所经过数字的最小和,每次只能向下侧和右侧移动一步
分析:
数塔模型,动态规划,
除了首行和首列外,每个位置只能由上侧或者左侧到达,则对于每个位置只需要比较并保留最优的结果即可
代码:(时间复杂度 O(n^2),空间复杂度O(1))
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int n = grid.size();
if (!n) {
return 0;
}
int m = grid[0].size();
for (int i = 1; i < m; ++ i) {
grid[0][i] += grid[0][i - 1];
}
for (int i = 1; i < n; ++ i) {
grid[i][0] += grid[i - 1][0];
}
for (int i = 1; i < n; ++ i) {
for (int j = 1; j < m; ++ j) {
grid[i][j] += min(grid[i][j - 1], grid[i - 1][j]);
}
}
return grid[n - 1][m - 1];
}
};