[leetcode]198. House Robber
Analysis
周五啦~—— [高考结束了耶~]
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个房子,如果抢劫那么就不能抢劫第i-1个房子,所以动态转移方程为:dp[i] = max(dp[i-1], dp[i-2]+nums[i-1])。
Implement
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if(len == 0)
return 0;
int* dp = new int[len+1];
dp[0] = 0;
dp[1] = nums[0];
for(int i=2; i<=len; i++){
dp[i] = max(dp[i-1], dp[i-2]+nums[i-1]);
}
return dp[len];
}
};