Leetcode Dungeon Game(经典动态规划)
来源:互联网 发布:2016淘宝域名怎么设置 编辑:程序博客网 时间:2024/05/20 13:19
class Solution {public: int calculateMinimumHP(vector<vector<int> > &dungeon) { int n = dungeon.size(); if(n <= 0){ return 0; } int m = dungeon[0].size(); if(m <= 0){ return 0; } int f[2][m]; f[(n-1) & 1][m - 1] = dungeon[n - 1][m - 1]; for(int j = m - 2; j >= 0; j--){ f[(n-1) & 1][j] = dungeon[n - 1][j] + min(0, f[(n-1) & 1][j + 1]); } for(int i = n - 2; i >= 0; i--){ f[i & 1][m - 1] = dungeon[i][m - 1] + min(0, f[i & 1 ^ 1][m - 1]); for(int j = m - 2; j >= 0; j--){ f[i & 1][j] = dungeon[i][j] + min(0, max(f[i & 1 ^ 1][j],f[i & 1][j + 1])); } } return 1 + (f[0][0] >0 ? 0 : abs(f[0][0])); }};
如果允许修改dungeon数组,那么我们甚至可以得到一个O(1)空间的解决方案
class Solution {public: int calculateMinimumHP(vector<vector<int> > &dungeon) { int n = dungeon.size(); if(n <= 0){ return 0; } int m = dungeon[0].size(); if(m <= 0){ return 0; } for (int i = n - 1; i >= 0; i--) { for (int j = m - 1; j >= 0; j--) { bool rowEnd = i == n - 1; bool columnEnd = j == m - 1; if (!rowEnd && !columnEnd) { dungeon[i][j] += max(dungeon[i + 1][j], dungeon[i][j + 1]); } else if (rowEnd ^ columnEnd) { dungeon[i][j] += dungeon[i + (rowEnd ? 0 : 1)][j + (columnEnd ? 0 : 1)]; } dungeon[i][j] *= !(dungeon[i][j] > 0); } } return abs(dungeon[0][0]) + 1; }};
0 0
- Leetcode Dungeon Game(经典动态规划)
- 算法学习之动态规划(leetcode 174. Dungeon Game)
- Dungeon Game 动态规划
- 【动态规划】Dungeon Game
- Leetcode.174 Dungeon Game |算法解析——动态规划
- 174. Dungeon Game-动态规划
- leetcode 174. Dungeon Game 一个逆着推导计算的DP动态规划问题
- LeetCode (23) Jump Game (动态规划)
- LeetCode Climbing Stairs(经典动态规划)
- LeetCode 题解(83): Dungeon Game
- LeetCode 174. Dungeon Game(游戏)
- Leetcode 174 - Dungeon Game(二分+dp)
- [leetcode] Dungeon Game
- leetcode 174: Dungeon Game
- [leetcode 174] Dungeon Game
- [leetcode] Dungeon Game
- Leetcode Dungeon Game
- LeetCode Dungeon Game
- HDU 1257 最少拦截系统 【LIS】
- 边采集边上传
- Python用subprocess的Popen来调用系统命令
- 58搜索公开的群聊的布局
- 是什么阻止了优化
- Leetcode Dungeon Game(经典动态规划)
- java定时任务:oracle导出excel后,发送excel作为附件的邮件
- vc6开发activex并发布全攻略(一)(初级篇)(原创)
- [IOS] 静态库项目之间的相互引用
- activty的生命周期
- 重构机房拦路虎(一)- 未能加载文件或程序集“DAL”或它的某一个依赖项。系统找不到指定的文件
- Eclipse调试Java程序技巧
- 禁止debian自动启动图形界面
- Unpublish