等级: medium
标签: 动态规划
思路
使用dp[i][j]表示从grid[i][j]到grid[m][n]的最小cost
dp[i][j]=⎧⎩⎨⎪⎪⎪⎪⎪⎪grid[i][j]grid[i][j]+dp[i+1][j]grid[i][j]+dp[i][j+1]min{grid[i][j]+dp[i+1][j],grid[i][j]+dp[i][j+1}i=m且j=nj=n且i<mi=m且j<ni<m且j<n
时间复杂度为
O(n2)
实现
class Solution {
public:
int minPathSum(vector<vector<int> >& grid) {
if(grid.empty()) return 0;
if(grid[0].empty()) return 0;
int m = grid.size(), n = grid[0].size();
vector< vector<int> > dp(m, vector<int>(n, 0));
for(int i = m - 1; i >= 0; i--)
for(int j = n - 1; j >= 0; j--) {
if(i == m - 1) {
if(j == n - 1) dp[i][j] = grid[i][j];
else dp[i][j] = dp[i][j + 1] + grid[i][j];
} else {
if(j == n - 1) dp[i][j] = dp[i + 1][j] + grid[i][j];
else dp[i][j] = min(grid[i][j] + dp[i + 1][j], grid[i][j] + dp[i][j + 1]);
}
}
return dp[0][0];
}
};