题目:
· 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.
思考:
这一道题是一道比较简单的动态规划,只需要计算从0开始到后面每一间房最大的金钱总数即可。动态转移方程为比较获取第i个房间的金钱加上i-2之前的金钱总数,以及获取i-1之前的金钱总数哪个大,就为0-i间房的最大金额。
代码:
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size()<1){
return 0;
}
vector<vector<int>> dp(nums.size(), vector<int>(nums.size()));
int i;
for (i = 0; i<nums.size(); i++){
dp[i][i] = nums[i];
}
for (i = 1; i<nums.size(); i++){
if(i<2){
dp[0][i] = nums[0]>nums[i] ? nums[0] : nums[i];
}else{
dp[0][i] = dp[0][i - 1] > dp[0][i - 2] + dp[i][i] ? dp[0][i - 1] : dp[0][i - 2] + dp[i][i];
}
}
return dp[0][nums.size() - 1];
}
};
结果: