174. Dungeon Game
这道题很有意思,是从后往前的dp,这道题其实一看就知道是dp,不过要从后往前去做还是有点难想到的。
class Solution(object):
def calculateMinimumHP(self, dungeon):
"""
:type dungeon: List[List[int]]
:rtype: int
"""
# dp[i][j] the minimum hp for i,j to go to the last block
if not dungeon:
return 0
d = dungeon
m = len(d)
n = len(d[0])
dp = [[sys.maxint for _ in range(n)] for _ in range(m)]
dp[m-1][n-1] = max(1, 1-d[m-1][n-1])
# initialize
for i in range(m-2, -1, -1):
dp[i][n-1] = max(1, dp[i+1][n-1] - d[i][n-1])
for j in range(n-2, -1, -1):
dp[m-1][j] = max(1, dp[m-1][j+1] - d[m-1][j])
# loop
for i in range(m-2, -1, -1):
for j in range(n-2, -1, -1):
down = max(1, dp[i+1][j] - d[i][j])
right = max(1, dp[i][j+1] - d[i][j])
dp[i][j] = min(down, right)
return dp[0][0]