网上都是从右下角向左上角进行dp的,我想了想,从左上角开始应该也可以,只不过要加边界判断条件(是否碰到dungeon的上边界或者左边界),很麻烦,从右下角开始确实简便了很多
class Solution {
public:
int calculateMinimumHP(vector<vector<int> > &dungeon) {
int M = dungeon.size();
int N = dungeon[0].size();
// hp[i][j] represents the min hp needed at position (i, j)
// Add dummy row and column at bottom and right side
vector<vector<int> > hp(M + 1, vector<int>(N + 1, INT_MAX));
hp[M][N - 1] = 1;
hp[M - 1][N] = 1;
for (int i = M - 1; i >= 0; i--) {
for (int j = N - 1; j >= 0; j--) {
int need = min(hp[i + 1][j], hp[i][j + 1]) - dungeon[i][j];
hp[i][j] = need <= 0 ? 1 : need;//如果need<=0,说明只要活着到dungeon[i][j]就行了,所以到dungeon[i][j]的时候生命值是1就行
}
}
return hp[0][0];
}
};