题目连接: https://leetcode.com/problems/dungeon-game/description/
题目分析: 使用一个数组health[][]记录Knight在每一个方格所需要 的最小health值,使用动态规划,通过动态转换方程:health[i][j] = min(health[i][j + 1], health[i + 1][j]) - dungeon[i][j] <= 0 ? 1 : min(health[i][j + 1], health[i + 1][j]) - dungeon[i][j],从dungeon的右下向左上进行状态的迁移,最终,Knight所需要的最小health值为health[0][0]。
代码:
class Solution {
public:
int calculateMinimumHP(vector<vector<int> >& dungeon) {
int m = dungeon.size(), n = dungeon[0].size();
int health[m][n];
health[m-1][n-1] = dungeon[m-1][n-1] > 0 ? 1 : abs(dungeon[m-1][n-1]) + 1;
for (int i = 0; i < n-1; ++i) {
int need = health[m-1][i+1] - dungeon[m-1][i];
health[m-1][i] = need <= 0 ? 1 : abs(need);
}
for (int i = 0; i < m-1; ++i) {
int need = health[i+1][n-1] - dungeon[i][n-1];
health[i][n-1] = need <= 0 ? 1 : abs(need);
}
for (int i = m-2; i >= 0; --i)
for (int j = n-2; j >= 0; --j) {
int need = min(health[i][j+1], health[i+1][j]) - dungeon[i][j];
health[i][j] = need <= 0 ? 1 : abs(need);
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
cout << health[i][j] << " ";
return health[0][0];
}
};
复杂度: O(m*n).