LeetCode[213] House Robber II

Note: This is an extension of House Robber.

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.


不能搶相鄰的房子,nums開頭和結尾相鄰,不能同時搶,於是可以分到兩個不同的數組裏。然後每個數組用動態規劃,狀態方程爲

dp[i] = max(dp[i - 1], dp[i - 2] + nums[i + start]);

class Solution {
public:
	int rob(vector<int>& nums) {
		if (nums.size() <= 1)
			return nums.empty() ? 0 : nums[0];
		return max(HouseRob(nums, 0, nums.size() - 2), HouseRob(nums, 1, nums.size() - 1));
	}
	int HouseRob(vector<int>& nums, int start, int end) {
		if (start == end)
			return nums[start];
		vector<int> dp(nums.size() - 1, 0);
		dp[0] = nums[start];
		dp[1] = max(nums[start], nums[start + 1]);
		for (int i = 2; i < nums.size() - 1; ++i)
		{
			dp[i] = max(dp[i - 1], dp[i - 2] + nums[i + start]);
		}
		return dp[nums.size() - 2];
	}
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章