【leetcode】198. House Robber
2016-08-06 20:12
393 查看
一、题目描述
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];
}
};
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(打家劫舍)Python
- 【LeetCode】 198. House Robber
- [LeetCode]198. House Robber I&II
- 【LeetCode题解】198. House Robber
- LeetCode 198. House Robber
- LeetCode 198. House Robber - 贪心算法
- leetcode198. House Robber
- leetcode 198. House Robber 入室抢劫 + DP动态规划求解
- LeetCode 198. House Robber
- LeetCode 198. House Robber
- leetcode 198. House Robber
- LeetCode 198. House Robber (Easy)
- LeetCode 198. House Robber
- [LeetCode]198. House Robber (JavaScript)
- LeetCode 198. House Robber
- LeetCode198. House Robber
- leetcode 198. House Robber(DP问题)
- leetcode 198. House Robber
- LeetCode -- 198. House Robber