64. Minimum Path Sum
64. 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.
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.
解析
// add 64. Minimum Path Sum
class Solution_64 {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
for (int i = 0; i < m;i++)
{
for (int j = 0; j < n;j++)
{
if (i==0&&j==0)
{
dp[i][j] = grid[0][0];
}else if (i==0)
{
dp[i][j] = dp[i][j - 1]+grid[i][j];
}
else if (j==0)
{
dp[i][j] = dp[i-1][j] + grid[i][j];
}
else
{
dp[i][j] = min(dp[i-1][j], dp[i][j - 1]) + grid[i][j];
}
}
}
return dp[m-1][n-1];
}
};
- O(n)空间
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> pre(m, grid[0][0]);
vector<int> cur(m, 0);
for (int i = 1; i < m; i++)
pre[i] = pre[i - 1] + grid[i][0];
for (int j = 1; j < n; j++) {
cur[0] = pre[0] + grid[0][j];
for (int i = 1; i < m; i++)
cur[i] = min(cur[i - 1], pre[i]) + grid[i][j];
swap(pre, cur);
}
return pre[m - 1];
}
题目来源
C/C++基本语法学习
STL
C++ primer