[week 11][Leetcode][Dynamic Programming] House Robber
来源:互联网 发布:剑三男神脸数据 花哥 编辑:程序博客网 时间:2024/05/22 13:01
- Question:
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 andit 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 tonightwithout alerting the police.
- Analysis:
这是一道关于动态规划的题目,需要求出小偷一个晚上最多可以偷到的金钱数目。举个例子将会很容易看出其中的关系,比如一条街上每户人家的金额为[6,12,8,9,10,4,3]。首先从第一,二户人家中选择一户进行偷盗,所以金额不变,到第三户人家时,此时小偷可以偷到的最大金额为:6,12,14,9,10,4,3;到第四户人家时,小偷只需要考虑排在他之前的第二和第三户人家的金额,此时他偷盗第四户时可以偷盗的最大金额为:6,12,14,21,10,4,3;以此类推,到第五户人家时:6,12,14,21,24,4,3;第六户:6,12,14,21,24,25,3;最后一户:6,12,14,21,24,25,27。所以一个晚上他可以偷盗且不会引起报警的金额为27。由这个例子我们可以明显看出其状态转移方程为:F[n] = max{F[n-2],F[n-3]} + F[n]。代码如下所示。
- Code:
class Solution {public: int rob(vector<int>& nums) { const int n = nums.size(); int result = 0; if (n==0) return 0; if (n == 1) return nums[0]; if (n == 2) { result = max(nums[0],nums[1]); return result; } if (n == 3) { result = max(nums[1],(nums[0]+nums[2])); return result; } if (n >= 4) { nums[2] += nums[0]; result = nums[2]; for (int i=3;i<n;i++) { nums[i] = max(nums[i-2],nums[i-3])+nums[i]; result = max(result,nums[i]); } return result; } }};
阅读全文
0 0
- [week 11][Leetcode][Dynamic Programming] House Robber
- LeetCode: -Dynamic Programming-House Robber[198]
- Dynamic Programming:198. House Robber
- [Leetcode刷题总结系列][Dynamic programming]198. House Robber
- (M)Dynamic Programming:213. House Robber II
- Leetcode:198. House Robber(week 9)
- LeetCode-Easy部分中标签为Dynamic Programming *198. House Robber
- [week 7][Leetcode][Dynamic Programming]Triangle
- [week 8][Leetcode][Dynamic Programming] Maximum Subarray
- [week 10][Leetcode][Dynamic Programming] Climbing Stairs
- [week 12][Leetcode][Dynamic Programming] Unique Paths
- 【dp】Leetcode House Robber&& House Robber II
- 【leetcode】House Robber && House Robber II
- LeetCode --- House Robber & House Robber II
- LeetCode OJ House Robber
- Leetcode: House Robber
- Leetcode 198: House Robber
- House Robber - LeetCode
- 开课第四天
- 存储过程的简单分析
- 2017.6.25
- Codeforces 821 D. Okabe and City
- 【计网】-- 概述
- [week 11][Leetcode][Dynamic Programming] House Robber
- rem与em的区别及rem的js算法
- JavaWeb学习总结(三)——Tomcat服务器学习和使用(二)
- C/C++堆栈模型 转载两篇经典
- 线程的状态
- Android之Activity生命周期
- Spring的学习
- java单元测试——JUnit4Hamcrest
- 初试cocos