LeetCode -- 198. House Robber
来源:互联网 发布:lol网络关注 编辑:程序博客网 时间:2024/06/05 17:43
题目:
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.
思路:
这道题是一个动态规划题,既然是动态规划,那么就得找到状态转移方程,这道题本质是求不相邻数组元素的最大组合问题,考虑抢劫到第i
家时,抢到的总钱数dist[i]
,第i
家抢与不抢只与i-1
是否被抢有关。所以:
初始时:
此时问题就被完美解决了。
C++实现:
class Solution {public: int rob(vector<int>& nums) { if(nums.size()==0) return 0; if(nums.size()==1) return nums[0]; vector<int> dist(nums.size(), 0); dist[0] = nums[0]; dist[1] = max(nums[0], nums[1]); for(int i=2; i<nums.size(); ++i){ dist[i] = max(dist[i-1], dist[i-2]+nums[i]); } return dist[nums.size()-1]; }};
- [LeetCode]198.House Robber
- 【LeetCode】198. House Robber
- 【LeetCode】198.House Robber
- LeetCode 198. House Robber
- [leetcode] 198.House Robber
- [leetcode] 198. House Robber
- LeetCode:198. House Robber
- 198. House Robber LeetCode
- [LeetCode]198. House Robber
- LeetCode || 198. House Robber
- LeetCode-198. House Robber
- [LeetCode]198. House Robber
- 【LeetCode】198. House Robber
- LeetCode#198. House Robber
- LeetCode 198. House Robber
- leetcode 198. House Robber
- LeetCode *** 198. House Robber
- leetcode 198. House Robber
- HDU 6040 Hints of sd0061 找第K大数 (nth_element函数)
- js里添加html调用function参数问题
- 模拟天猫--网页定位导航效果
- Linux中三种网络模式是什么意思——NAT(二地址转换模式)
- CodeForces 803C
- LeetCode -- 198. House Robber
- PHP与表单的简单应用
- Python3之内置函数
- 自定义控件三部曲之动画篇(九)——联合动画的代码实现
- 2017华为机试(仿LISP字符串运算)
- C++中的const声明
- python3+eclipse+pydev环境搭建
- 原生js仿百度搜索框
- vnc