The demons had captured the princess (P) and imprisoned her inthe bottom-right corner of a dungeon. The dungeon consists of M x N rooms laid out in a 2D grid. Our valiant knight (K) was initially positioned inthe top-left room and must fight his way throughthe dungeon to rescue the princess.
The knight has an initial health point represented by a positive integer. If at any point his health point drops to0orbelow, he dies immediately.
Some ofthe rooms are guarded by demons, so the knight loses health (negative integers) upon entering these rooms; other rooms are either empty (0's) orcontain magic orbs that increase the knight's health (positive integers).
In order to reach the princess as quickly as possible, the knight decides to move only rightward or downward in each step.
Write a function to determine the knight's minimum initial health so that he is able to rescue the princess.
For example, giventhe dungeon below, the initial health ofthe knight must be at least 7if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
class Solution {
public:
int minSubSequenceSum(vector<int> nums){
int n = nums.size();
int thisSum = 0;
int minSum = 0;
for(int i = 0;i < n;++i){
thisSum += nums[i];
minSum = thisSum < minSum?thisSum:minSum;
if(thisSum > 0){
thisSum = 0;
continue;
}
}
return minSum;
}
int minSubSequenceSum_1(vector<int> nums){
int n = nums.size();
vector<int> dp[n+1];
int min = 0;
dp[n] = 0;
for(int i = n-1;i >= 0;--i){
int min = dp[i+1] - nums[i] ;
dp[i] = min <= 0?0:min;
}
return dp[0];
}
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int n = dungeon.size();
int m = dungeon[0].size();
if(n <= 0){
return0;
}
vector<int> t(m+1,INT_MAX);
vector<vector<int>> hp(n+1,t);
int need = 0;
/*intitial*/
hp[n-1][m] = 1;
hp[n][m-1] = 1;
for(int i = n-1;i >= 0;--i){
for(int j = m-1;j >= 0;--j){
int need = min(hp[i+1][j],hp[i][j+1]) - dungeon[i][j];//min one is need the morest HP
hp[i][j] = need <= 0?1:need;
}
}
return hp[0][0];
}
};