Minimum Path Sum 题解
题目来源:Minimum Path Sum
> 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.
解题思路:
递归
用递归思路比较清晰,然后转成迭代。
int min(vector<vector<int> >&grid, int row, int col)
{
if(row == 0)
{
int result = 0;
for(int i = 0; i <= col; i++)
result += grid[0][i];
return result;
}
if(col == 0)
{
int result = 0;
for(int i = 0; i <= row; i++)
result += grid[i][0];
return result;
}
int fromleft = min(grid, row, col-1);
int fromup = min(grid, row-1, col);
return std::min(fromleft, fromup);
}动态规划, O(m+n)空间
动态规划, O(n)空间
更加节约点空间可以这样. 参考了leetcode-cpp
Last updated
Was this helpful?