题目链接:https://leetcode.com/problems/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.
解析:先搞懂题意:也就是说不能偷连续的两家,用动态规划的思想,动态规划关键要找到递推公式,要学会分析,对于第i家要么偷要么不偷,到第i家,偷的最多的钱有两种可能:偷第i家,那么不能偷i-1家,money[i][1]=money[i-1][0]+nums[i]
不偷第i家,那么i-1家可以偷也可以不偷,money[i][0]=max{money[i-1][1],money[i-1][0]}
动态规划题重要的是思路,是递推公式!!!如何把问题分解为小问题!!!需要多做!!!总是没思路。。。
代码:
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n==0)
return 0;
vector<int> rob(1,nums[0]);
vector<int> nrob(1,0);
for (int i = 1; i<n; i++)
{
nrob.push_back(rob[i - 1]>nrob[i - 1] ? rob[i - 1] : nrob[i - 1]);
rob.push_back(nrob[i - 1]+nums[i]);
}
return nrob[n - 1]>rob[n - 1] ? nrob[n - 1] : rob[n - 1];
}
};