题目:
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.
思路:
1. 处理边界情况
2. 典型的动态规划问题,当然也可以用递归做,但是DP明显的用时短
3. 对于任意一个点,他的最短路径必然包括自己的值,再加上左边或者上边的最短路径即到达改点的最短路径
代码:
int minPathSum(vector<vector<int>>& grid) {
//动态规划问题
if (grid.size() == 0) return 0;
vector<vector<int>> res(grid); //复制
//将最外边两列的长度求出,方便内层循环求路径
for (int i = 1; i < grid.size(); i++) res[i][0] += res[i - 1][0];
for (int i = 1; i < grid[0].size(); i++) res[0][i] += res[0][i - 1];
for (int i = 1; i < grid.size(); i ++)
for(int j = 1; j < grid[0].size(); j++)
res[i][j] = res[i][j] + min(res[i - 1][j], res[i][j - 1]);
return res[grid.size() - 1][grid[0].size() - 1];
}