您的位置:首页 > 其它

[LeetCode] House Robber II

2015-08-15 11:23 363 查看
This problem is a little tricky at first glance. However, if you have finished the House Robberproblem, this problem can simply be decomposed into two House Robber problems. Suppose there are
n
houses, since house
0
and
n - 1
are now neighbors, we cannot rob them together and thus the solution is now the maximum of

Rob houses
0
to
n - 2
;

Rob houses
1
to
n - 1
.

The code is as follows. Some edge cases (
n <= 2
) are handled explicitly.

class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if (n <= 2) return n ? (n == 1 ? nums[0] : max(nums[0], nums[1])) : 0;
return max(robber(nums, 0, n - 2), robber(nums, 1, n -1));
}
private:
int robber(vector<int>& nums, int l, int r) {
int pre = 0, cur = 0;
for (int i = l; i <= r; i++) {
int temp = max(pre + nums[i], cur);
pre = cur;
cur = temp;
}
return cur;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: