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 1:
[[1,3,1], [1,5,1], [4,2,1]]Given the above grid map, return
7
. Because the path 1→3→1→1→1 minimizes the sum.
leetcode上做题还是蛮有成就感的。独立思考完成的第三题。解题思路:与unique paths有些类似。建立一个二维数组保存每种grid下的路径的最小和。并且,下一步的最小和依赖于上一步的最小和。得到了递推式:
mins[i][j] = grid[i][j] + min(mins[i-1][j],mins[i][j-1]);
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
vector<vector<int>> mins(grid.size(), vector<int>(grid[0].size(), 0));
//初始化,没有成功?访问vector越界
mins[0][0] = grid[0][0];
for (int i = 1; i < grid[0].size(); i++)
{
mins[0][i] = mins[0][i - 1] + grid[0][i];
}
for (int i = 1; i < grid.size(); i++)
{
mins[i][0] = mins[i - 1][0] + grid[i][0];//vector访问不要越界了
}
if(grid.size()>1)
for (int i = 1; i < grid.size(); i++)
for (int j = 1; j < grid[0].size(); j++)//注意访问的起始下表
{
mins[i][j] = grid[i][j] + min(mins[i-1][j],mins[i][j-1]);
}
return mins[grid.size()-1][grid[0].size()-1];
}
};