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.
给定一个矩阵,从左上角走到右下角,步数最少的走法。
刚开始用的是贪心,从右下角往左上角走,每次要么向上要么想左,所以每次选择数值最小的方向来走。但是这个方法结果不对。
看到讨论区有用动态规划来做的。先将第一行和第一列的步数都算出来,然后再求当前位置从哪个地方过来总步数最少。
先贴正确的代码,用动态规划做。
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
vector<vector<int>> cost (grid.size(),vector<int>(grid[0].size(),0));
cost[0][0] = grid[0][0];
for(int i=1;i<grid.size();i++){
cost[i][0] = cost[i-1][0] + grid[i][0];
}
for(int j=1;j<grid[0].size();j++){
cost[0][j] = cost[0][j-1] + grid[0][j];
}
for(int i=1;i<grid.size();i++)
for(int j=1;j<grid[0].size();j++){
cost[i][j] = min(cost[i-1][j],cost[i][j-1])+grid[i][j];
}
return cost[grid.size()-1][grid[0].size()-1];
}
};