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.
解题思路
这是一道经典DP题,从左上角走到右下角,求所需要的最小话费。DP表达式如下:
<pre>
dp[i][j] = min(dp[i-1][j],dp[i][j-1])+grid[i][j];
</pre>
可对代码进行适当优化减少空间开销。
代码
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int width = grid.size();
int height = grid[0].size();
int a[2][height];
a[0][0] = grid[0][0];
for (int i=1;i<height;i++){
a[0][i] = a[0][i-1]+grid[0][i];
}
for (int i=1;i<width;i++){
a[i%2][0] = a[(i-1)%2][0]+grid[i][0];
for (int j=1;j<height;j++){
a[i%2][j] = min(a[(i-1)%2][j],a[i%2][j-1])+grid[i][j];
}
}
return a[(width-1)%2][height-1];
}
};