题目
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.
分析
可以延续第62、63两道题的思想,从后往前逆推。不同的是,这次要取其后面可能路径中最小的值,并且加上自身的值。
实现
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
if(grid.empty()||grid[0].empty()) return 0;
int m=grid.size(), n=grid[0].size();
int dp[m][n];
dp[m-1][n-1] = grid[m-1][n-1];
for(int i=m-2; i>=0; i--)
dp[i][n-1] = dp[i+1][n-1] + grid[i][n-1];
for(int i=n-2; i>=0; i--)
dp[m-1][i] = dp[m-1][i+1] + grid[m-1][i];
for(int i=m-2; i>=0; i--)
for(int j=n-2; j>=0; j--)
dp[i][j] = min(dp[i][j+1], dp[i+1][j]) + grid[i][j];
return dp[0][0];
}
};
思考
感觉这种类型的题基本没问题了呀(flag已立……)。
网友评论