1,题目要求
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.
给定m x n网格填充非负数,找到从左上到右下的路径,这最小化了沿其路径的所有数字的总和。
注意:您只能在任何时间点向下或向右移动。
2,题目思路
对于这道题,跟上一道题很类似,也是求路径的问题,不过不是求路径的总的数量,而是到达终点的最小代价。
因为行走的限制——只能向右走或者向下走,因此也跟上一题一样,最上面一行和最左边一列的行走方式是确定的,于是行走代价也是确定的。
同时,动态规划的函数也比较好确定:
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m= grid.size();
int n = grid[0].size();
vector<vector<int>> sumDP (m, vector<int> (n, grid[0][0]));
for(int i = 1;i<m;i++)
sumDP[i][0] = sumDP[i-1][0] + grid[i][0];
for(int j = 1;j<n;j++)
sumDP[0][j] = sumDP[0][j-1] + grid[0][j];
for(int i = 1;i<m;i++)
for(int j = 1;j<n;j++)
sumDP[i][j] = min(sumDP[i-1][j], sumDP[i][j-1]) + grid[i][j];
return sumDP[m-1][n-1];
}
};