week16-leetcode #198-House Robber
链接:https://leetcode.com/problems/house-robber/description/
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 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
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.
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.
Note
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
Solution
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if (size == 0) {
return 0;
} else if (size == 1) {
return nums[0];
} else if (size == 2) {
return max(nums[0], nums[1]);
}
int* dp = new int[size];
dp[0] = nums[0];
dp[1] = max(nums[0], nums[1]);
for (int i = 2; i < size; i++) {
dp[i] = max(dp[i-2]+nums[i], dp[i-1]);
}
return dp[size-1];
}
};
思路:使用动态规划的方法,其实问题可以转化为如何在一个数组中挑出不相邻的数字最大和。定义dp[i]为前i个房子获得的金钱的最大值,显然,前i个房子获得的金钱的最优解可能是前i-1个房子的最优解或者是前i-2个房子的最优解加上第i个房子的金钱。所以轻易得到转移方程如下:
dp[i]=max{dp[i−1],dp[i−2]+nums[i]} d p [ i ] = m a x { d p [ i − 1 ] , d p [ i − 2 ] + n u m s [ i ] }