题目:
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.
翻译:
m*n的数组,找一条从左上角到右下角的路径,使得路径上所有数字的和最小。(行走的策略限定在每步只能向右或者向下)
思路:
这题是比较明显地能用动态规划的题,而且代码也比较好写。重构一个m*n数组a,a[i][j]代表从左上角到当前位置的最小数字之和。当i>0且j>0时,a[i][j]=min(a[i-1][j],a[i][j-1])+nums[i][j]。最后填满整个数组之后,只要返回a[nums.size()-1][nums[0].size()-1]的值即可。
代码:
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.size()==0)
return 0;
vector<vector<int>> path;
path.resize(grid.size());
for(int i=0;i<path.size();i++)
{
path[i].resize(grid[0].size());
}
for(int i=0;i<path.size();i++)
{
for(int j=0;j<path[0].size();j++)
{
if(i==0 && j==0)
path[i][j]=grid[i][j];
else if(j==0)
path[i][j]=path[i-1][j]+grid[i][j];
else if(i==0)
path[i][j]=path[i][j-1]+grid[i][j];
else
{
path[i][j]=min(path[i-1][j],path[i][j-1])+grid[i][j];
}
}
}
return path[grid.size()-1][grid[0].size()-1];
}
};
结果: