【leetcode】198. House Robber
来源:互联网 发布:虚拟币场外交易源码 编辑:程序博客网 时间:2024/06/13 16:20
一、题目描述
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 个房间有两种策略,一种是盗窃一种是不盗窃。设置一个数组dp[i] 代表在第 i 个房子时达到的最大的收益。那么对于dp[i]有两种计算:
(1)如果盗窃第 i 个房子,那么对于第 i-1 个房子肯定是不盗窃的,因此dp[i] = dp[i-2] + nums[i]
(2)如果不盗窃第 i 个房子,那么dp[i] = dp[i-1]
所以dp[i] = max(dp[i-2]+nums[i], dp[i-1])
c++代码(0ms,18.62%)
class Solution {public: int rob(vector<int>& nums) { int len=nums.size(); if(len==0) return 0; int *dp=new int[len]; dp[0]=nums[0]; dp[1]=max(dp[0], nums[1]); for(int i=2; i<len; i++){ dp[i] = max(dp[i-1], dp[i-2]+nums[i]); } return dp[len-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
- HDU2089(数位DP)
- Qt窗口像QQ在屏幕顶端自动隐藏
- poj2299Ultra-QuickSort(归并求逆序数)
- 「Deep Learning」FCN - Fully Convolutional Networks
- (HDU 3032) Nim or not Nim(SG函数、博弈)
- 【leetcode】198. House Robber
- 数据结构学习笔记(十)哈希表(散列表)
- hdu NanoApe Loves Sequence
- sql语句那些事儿—mysql 又见存储过程
- poj 1321 棋盘问题
- java面试题集
- mnist_train_test.prototxt代码解析
- 你的linux机器上 grep xxx -rl ./ 会递归吗?
- 常见排序的最好,平均以及最坏时间复杂度