题目
代码(首刷看解析 2024年5月6日)
class Solution {
public:
// 动态规划
int calculateMinimumHP(vector<vector<int>>& dungeon) {
// dp[i][j]从(i,j)出发,到达终点所需要的最少血量
int m = dungeon.size();
int n = dungeon[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
// dp[i][j] = max(0, min(dp[i + 1][j], dp[i][j + 1] - dungeon[i][j]));
dp[m - 1][n - 1] = max(0, -dungeon[m - 1][n - 1]);
for (int i = m - 2; i >= 0; i--) {
dp[i][n - 1] = max(dp[i + 1][n - 1] - dungeon[i][n - 1], 0);
}
for (int j = n - 2; j >= 0; j--) {
dp[m - 1][j] = max(dp[m - 1][j + 1] - dungeon[m - 1][j], 0);
}
for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
dp[i][j] = max(0, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
}
}
return dp[0][0] + 1;
}
};
代码(二刷自解 2024年8月12日)
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int m = dungeon.size();
int n = dungeon[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[m - 1][n - 1] = max(0, -dungeon[m - 1][n - 1]);
for (int i = m - 2; i >= 0; i--) {
dp[i][n - 1] = max(dp[i + 1][n - 1] - dungeon[i][n - 1], 0);
}
for (int j = n - 2; j >= 0; j--) {
dp[m - 1][j] = max(dp[m - 1][j + 1] - dungeon[m - 1][j], 0);
}
for (int i = m - 2; i >= 0; i--) {
for (int j = n - 2; j >= 0; j--) {
dp[i][j] = max(0, min(dp[i + 1][j], dp[i][j + 1]) - dungeon[i][j]);
// cout<<"dp["<<i<<"]["<<j<<"]:"<<dp[i][j]<<" ";
}
// cout<<endl;
}
return dp[0][0] + 1;
}
};