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
题意
你是一个准备在街坊盗窃的专业小偷。每个房子都有一定的钱,你唯一的麻烦就是当相邻的两个房子被盗窃时,会自动联系警察。
给一个房子持有金额的列表,计算出你可以安全盗窃的最大金额。
题解
问题类型:动态规划
定义一个结构体
struct DP {
bool rob;
int value;
}
表示子结构:当前最大的盗窃金额,最后一个房子有没有被盗窃
那么转移方程就是:
dp[i].value = max(dp[i - 1].rob ? dp[i - 1].value : dp[i - 1].value + nums[i], dp[i - 2].value + nums[i]);
解在下方
struct DP {
bool rob;
int value;
};
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if (len == 0) return 0;
vector<DP> dp;
dp.resize(len);
dp[0].value = nums[0];
dp[0].rob = true;
if (len >= 2) {
dp[1].value = nums[0] > nums[1] ? nums[0] : nums[1];
dp[1].rob = nums[1] > nums[0];
}
for (int i = 2; i < len; i++) {
int f = dp[i - 1].value + (dp[i - 1].rob ? 0 : nums[i]);
int s = dp[i - 2].value + nums[i];
if (s > f || !dp[i - 1].rob) dp[i].rob = true;
else dp[i].rob = false;
dp[i].value = f > s ? f : s;
}
return dp[len - 1].value;
}
};
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。