动态规划
保证走到右下时血量至少为1
个人觉得备忘录memo和dp数组本质上没什么区别
存的是到当前格所需要的最少生命值,
具体见注释
class Solution {
int[][] memo;
public int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length;
int n = dungeon[0].length;
memo = new int[m][n];
for(int[] row:memo){
Arrays.fill(row,-1);
}
return dp(dungeon,0,0);
}
//走到当前格子所需要的最小生命值
public int dp(int[][] grid,int i,int j){
int m = grid.length;
int n = grid[0].length;
//base case(从右下到左上跑)
if(i == m-1&&j == n-1){
return grid[i][j] >=0 ?1:-grid[i][j]+1;
}
//如果超出边界了,就设置为需要无限生命
if(i == m||j==n){
return Integer.MAX_VALUE;
}
if(memo[i][j] != -1){
return memo[i][j];
}
//生命值核心公式
int res = Math.min(
dp(grid,i+1,j),
dp(grid,i,j+1)
)-grid[i][j];
memo[i][j] = res <= 0?1:res;
return memo[i][j];
}
}