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.
class Solution {
public:
int rows,cols;
int minPathSum(vector<vector<int> > &grid) {
if(!grid.size() || !grid[0].size())return 0;
rows = grid.size();
cols = grid[0].size();
vector<vector<int> >dp;
vector<int> v;
for(int i = 0; i < rows; i++)
{
v.clear();//vector二维初始化,不要像数组那样直接dp[i][j] = xx,越界,习惯!
for(int j = 0; j < cols; j++)
v.push_back(-1);
dp.push_back(v);
}
return minSum(0, 0, dp, grid);
}
int minSum(int r, int c, vector<vector<int> > &dp,vector<vector<int> > &grid)
{
if(r == rows - 1 && c == cols - 1)
{
dp[r][c] = grid[r][c];
return dp[r][c];
}
if(dp[r][c] != -1)return dp[r][c];
int rst = INT_MAX;
if(c < cols - 1)rst = grid[r][c] + minSum(r, c + 1, dp, grid);
if(r < rows - 1)rst = min(rst, grid[r][c] + minSum(r + 1, c, dp, grid));
dp[r][c] = rst;
return rst;
}
};
最小路径和算法解析

本文介绍了一个算法问题:在一个非负数构成的矩阵中寻找从左上角到右下角的路径,使得路径上的数字之和最小。文章详细解释了递归动态规划的方法,并提供了完整的C++代码实现。
316

被折叠的 条评论
为什么被折叠?



