LeetCode动态规划198. House Robber思路解析
来源:互联网 发布:linux初学者入门书籍 编辑:程序博客网 时间:2024/05/21 13:55
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
思路点拨
递归思想:
抢劫从编号为cur房子开始,到end结束,所获得的利益为:
a)在抢劫第cur房子时,int robed=nums[cur]+rob(cur+2,end),
b) 不抢劫cur房子时,int nonRobed=rob(cur+1,end)
c)返回max(robed,nonRobed),该值作为 抢劫起始编号为cur,结束为end的获得的最大利益。
c++代码实现
class Solution {public: int recurse(vector<int>& table, vector<int>& nums, int cur, int end) { if (cur> end) { return 0; } // 对于table中曾经通过递归确定了的值,不再判断是否rob if (-1 != table[cur]) { return table[cur]; } // 如果是rob,就把当前值加上 以cur+2开始的新的nums用来递归判断得到的最大值 作为rob时得到的最大值 int robed = nums[cur] + recurse(table, nums, cur + 2, end); // 如果是rob,就把 以cur+1开始的新的nums用来递归判断得到的最大值 作为没rob时得到的最大值 int nonRobed = recurse(table, nums, cur + 1, end); // 把2种情况对应的最大值中较大的一个作为 “强盗从当前house一直到street末尾的house可获得的最大值” table[cur] = (robed > nonRobed) ? robed: nonRobed; return table[cur]; } int rob(vector<int>& nums) { if (nums.empty()) { return 0; } int len = nums.size(); if (1 == len) { return nums[0]; } // 创建一个与house数量一致的table,table[i]表示从下标为i的house开始到最后一个house强盗可获得的最大财富值,初始化为-1,表示table[i]还未计算 vector<int> table(len, -1); // 递归判断每个table[i], 最后强盗所能获得的最大财富值就是table[0] return recurse(table, nums, 0, len -1); }};
- LeetCode动态规划198. House Robber思路解析
- LeetCode 198. House Robber 213. House Robber II--动态规划
- leetcode 198.House Robber-打家劫舍|动态规划
- 【Leetcode】198. House Robber - - 【动态规划】
- 198.leetcode House Robber(easy)[动态规划]
- 198. House Robber-leetcode+动态规划
- (动态规划)LeetCode#198. House Robber
- leetcode 198. House Robber | 动态规划
- LeetCode 198. House Robber (动态规划)
- Leetcode House Robber 动态规划
- [LeetCode][动态规划]House Robber
- 198. House Robber-动态规划
- LeetCode 198. House Robber 递归->记忆->动态规划 ->新思路
- 动态规划入门级教程(leetcode) 198.House Robber
- leetcode 198. House Robber 入室抢劫 + DP动态规划求解
- LeetCode 198House Robber动态规划
- [LeetCode 198] House Robber(动态规划)
- 【Leetcode】213. House Robber II 【动态规划】
- TCP 的那些事儿(下)
- 二进制32位ip地址转换为十进制表示
- UVA 11401Triangle Counting
- DOS命令行中常见的命令
- Bugtags工具试用过程笔记
- LeetCode动态规划198. House Robber思路解析
- 进程与线程区别,为什么进入进程机制?
- bootstrap modal 弹出失效
- UVALive 3516Exploring Pyramids
- Swift 中使用 SQLite——修改和删除数据
- 根据连续分布产生随机数一般方法
- ios面试试题总结(未整理)
- 第三届中国移动开发者大会(MDCON.2015)
- UVA 11361Investigating Div-Sum Property