LeetCode213 House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

思路:

这道题其实和他的第一个版本是一样的。但是因为有loop,我们需要考虑两种情况:打劫第一个house;不打劫第一个house。显然,针对两种情况我们分别调用使用一次解决第一个版本问题的方法就可以了。

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0) return 0;
		if (nums.size() == 1) return nums.back();
		int len = int(nums.size());
		vector<int> dp1(len, 0);
		vector<int> dp2(len, 0);
		vector<int> s1 = nums, s2 = nums;
		s1.front() = 0;
		s2.back() = 0;
		dp1[0] = s1[0], dp1[1] = max(s1[0], s1[1]);
		dp2[0] = s2[0], dp2[1] = max(s2[0], s2[1]);
		for (int i = 2; i < len; i++) {
			dp1[i] = max(dp1[i - 1], dp1[i - 2] + s1[i]);
			dp2[i] = max(dp2[i - 1], dp2[i - 2] + s2[i]);
		}
		return max(dp1.back(), dp2.back());
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/89316089
今日推荐