problem:https://leetcode.com/problems/dungeon-game
看了这道题的tag我用了二分 + 简化dp(只需求特定血量能否达到)来做,能过但是速度好慢。一看评论区发现大家都是用纯dp过的,我哭了。
class Solution { public: int m, n; bool canSave(vector<vector<int>>& dungeon, int life) { vector<vector<int>> health(m, vector<int>(n, -1)); health[0][0] = life + dungeon[0][0]; for(int i = 0;i < m ;i++) { for(int j = 0;j < n;j++) { if(i > 0 && health[i - 1][j] > 0) { health[i][j] = health[i - 1][j] + dungeon[i][j]; } if(j > 0 && health[i][j - 1] > 0) { health[i][j] = max(health[i][j], health[i][j - 1] + dungeon[i][j]); } } } return health[m - 1][n - 1] > 0; } int calculateMinimumHP(vector<vector<int>>& dungeon) { m = dungeon.size(); if(!m) return 0; n = dungeon[0].size(); int high = 1; int low = 1; for(int i = 0; i < m; i++) { for(int j = 0;j < n; j++) { if(dungeon[i][j] < 0) { high += -dungeon[i][j]; } } } while(low < high) { int mid = low + (high - low) / 2; if(canSave(dungeon, mid)) { high = mid; } else { low = mid + 1; } } return low; } };
原文地址:https://www.cnblogs.com/fish1996/p/11331035.html
时间: 2024-10-03 14:05:25