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:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
思路
动态规划问题
c++11
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
for (decltype(grid.size()) i = 0; i < grid.size(); ++i)
for (decltype(grid[0].size()) j = 0; j < grid[0].size(); ++j) {
if (i == 0 && j == 0) continue;
else if (i == 0) grid[i][j] += grid[i][j-1];
else if (j == 0) grid[i][j] += grid[i-1][j];
else grid[i][j] += std::min(grid[i-1][j], grid[i][j-1]);
}
return grid.back().back();
}
};
这里 decltype(grid.size())
和 decltype(grid[0].size())
的类型为 size_t
,也可直接使用。
动态规划
参见知乎上的讨论。