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.
思路:
一个简单的动态规划问题。位于(y, x)的最小路径和等于(y,x)点处的值加上(y-1, x)点或(y, x-1)点二者之间较小的那个值。填充一个m x n的表格即可得到解。
题解:
class Solution {
public:
int minPathSum(vector<vector<int> > &grid) {
if (grid.size() == 0 || grid[0].size() == 0)
return 0;
const size_t Y = grid.size();
const size_t X = grid[0].size();
// create the accumulative map
vector<vector<int>> pathSum(Y);
for(auto& v : pathSum)
v.resize(X);
// initialize the trigger
pathSum[0][0] = grid[0][0];
// such loop is not good
// since it does not exploit the cache
// but let it so
for(size_t x = 0; x < X; ++x)
for(size_t y = 0; y < Y; ++y)
{
if (x == 0 && y == 0)
continue;
int left = (x == 0 ? INT_MAX : pathSum[y][x - 1]);
int top = (y == 0 ? INT_MAX : pathSum[y - 1][x]);
pathSum[y][x] = min(left, top) + grid[y][x];
}
return pathSum[Y - 1][X - 1];
}
};