题目
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
class Solution {
public:
int rob(vector<int>& nums) {
}
};
思路
代码
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if (size == 0) {
return 0;
}
/*int* a = new int[size];
int* b = new int[size];
a[0] = 0;
b[0] = nums[0];
for (int i = 1; i < size; i++) {
b[i] = a[i-1]+nums[i];
a[i] = max(a[i-1], b[i-1]);
}
return max(a[size-1], b[size-1]);*/
int a = 0, b = nums[0];
for (int i = 1; i < size; i++) {
int tb = b, ta = a;
b = ta+nums[i];
a = max(ta, tb);
}
return max(a, b);
}
};
本文探讨了一种抢劫房屋的问题,其中相邻房屋安装了联动报警系统。通过动态规划的方法,文章提供了一个高效的解决方案来确定在不触发报警的情况下,能够获得的最大金额。
8万+

被折叠的 条评论
为什么被折叠?



