int minPathSum(vector<vector<int> > &grid) {
if (grid.empty())
{
return 0;
}
else if (grid[0].empty())
{
return 0;
}
vector<vector<int>> pathSum = grid;
int m = grid.size();
int n = grid[0].size();
int sum = 0;
for (int row = m-1,col = n-1; row >= 0; row--)
{
pathSum[row][col] += sum;
sum = pathSum[row][col];
}
sum = 0;
for (int row = m-1,col = n-1; col >= 0; col--)
{
pathSum[row][col] += sum;
sum = pathSum[row][col];
}
for (int row = m-2; row >= 0; row--)
{
for (int col = n-2; col >= 0; col--)
{
int min = pathSum[row+1][col] < pathSum[row][col+1] ? pathSum[row+1][col] : pathSum[row][col+1];
pathSum[row][col] += min;
}
}
return pathSum[0][0];
}
与前一题Unique Paths的方法基本相同。