方法1: 这道题应该是可以用backtracking来做的,但是我还是直接去尝试了dp。dp思路其实也不难,但是很可惜我想反了。我的想法是top-down,但是其实必须得bottom-up。但是我估计用backtracking的话top-down是可以的。anyway,这道题还是很不错的题目,方法1时间复杂mn,空间复杂mn。然后方法1的空间复杂可以优化,用一维dp数组就行,但是我现在不要求自己去看,先把二维给整熟练再说吧。具体思路直接看lc官方解答1.
class Solution {
int inf = Integer.MAX_VALUE;
int[][] dp;
int rows, cols;
public int getMinHealth(int currCell, int nextRow, int nextCol) {
if (nextRow >= this.rows || nextCol >= this.cols)
return inf;
int nextCell = this.dp[nextRow][nextCol];
// hero needs at least 1 point to survive
return Math.max(1, nextCell - currCell);
}
public int calculateMinimumHP(int[][] dungeon) {
this.rows = dungeon.length;
this.cols = dungeon[0].length;
this.dp = new int[rows][cols];
for (int[] arr : this.dp) {
Arrays.fill(arr, this.inf);
}
int currCell, rightHealth, downHealth, nextHealth, minHealth;
for (int row = this.rows - 1; row >= 0; --row) {
for (int col = this.cols - 1; col >= 0; --col) {
currCell = dungeon[row][col];
rightHealth = getMinHealth(currCell, row, col + 1);
downHealth = getMinHealth(currCell, row + 1, col);
nextHealth = Math.min(rightHealth, downHealth);
if (nextHealth != inf) {
minHealth = nextHealth;
} else {
minHealth = currCell >= 0 ? 1 : 1 - currCell;
}
this.dp[row][col] = minHealth;
}
}
return this.dp[0][0];
}
}
总结:
- 无