题目:174.地下城游戏
class Solution {
public int calculateMinimumHP(int[][] dungeon) {
int m = dungeon.length;
int n = dungeon[0].length;
int[][] dp = new int[m+1][n+1];
Arrays.fill(dp[m], Integer.MAX_VALUE);
for(int j=0; j<=m; j++)
dp[j][n] = Integer.MAX_VALUE;
dp[m-1][n] = 1;
dp[m][n-1] = 1;
for(int i=m-1; i>=0; i--)
for(int j=n-1; j>=0; j--)
dp[i][j] = Math.max(Math.min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j], 1);
return dp[0][0];
}
}
看到一位网友的C++代码也很简洁:
class Solution {
public:
int calculateMinimumHP(vector<vector<int>>& dungeon) {
int n=dungeon.size(),m=dungeon[0].size();
vector<vector<int>> dp(n+1,vector<int>(m+1,INT_MAX));
dp[n][m-1]=dp[n-1][m]=1;
for(int i=n-1;i>=0;i--){
for(int j=m-1;j>=0;j--){
dp[i][j]=max((min(dp[i+1][j],dp[i][j+1])-dungeon[i][j]),1);
}
}
return dp[0][0];
}
};
|