198. House Robber
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.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Approach
- 题目大意就是一个小偷要去民宅偷东西,但是不能偷相邻的。动态规划类专题,这是一道很经典的动态规划,我们来用简洁的故事一下描述一下动态规划的过程:首先确保民宅n>=3栋,小偷在第3栋房子停了下,他需要决定该偷第二栋房子还是偷两栋房子第一栋和这栋房子,这时就要比较他们价值,哪个大偷哪个,然后小偷继续走来到了第四栋房子,它该需要决定该偷第一栋房子和这栋房子,还是偷第三栋刚偷过的房子,还是偷第二栋房子和这栋房子呢,也是一样比较价值,所以小偷每走一栋就这样抉择,最后它能偷到最多东西,可能会有疑惑,为什么到第四栋开始要想前三栋的主意,因为有效相邻距离最大就是两栋,可以好好仔细想想,为什么不是三栋或者一栋,或者更多,或许故事讲的不大好,可以与代码共服会更好。
Code
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 0)return 0;
if (n == 1)return nums[0];
if (n == 2)return max(nums[0], nums[1]);
vector<int>dp(n, 0);
for (int i = 2; i < n; i++) {
if (i == 2)
nums[i] = max(nums[i - 2] + nums[i], nums[i - 1]);
else
nums[i] = max(max(nums[i-3]+nums[i],nums[i - 2] + nums[i]), nums[i - 1]);
}
return nums[n - 1];
}
};