算法分析與設計——LeetCode Problem.213 House Robber II

題目鏈接


問題描述


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.


解題思路


與Leetcode 198 題不同的是這題第一個房間與最後一個房間相連,即形成了一個環。那麼假如選擇第一個房間,那最後一個房間就不能進入;如果不選擇第一個房間,就存在進入最後一個房間的可能性。然後將這兩種情況得出的最大值進行比較,即得到最優解。

代碼如下

class Solution {
public:
	int rob(vector<int>& nums) {
		if (nums.size() == 0) return 0;
		if (nums.size() == 1) return nums[0];
		if (nums.size() == 2) return max(nums[0], nums[1]);

		int leng = nums.size();
		
		vector<int> vec1(leng - 1, 0);
		vector<int> vec2(leng, 0);
		
		vec1[0] = nums[0];
		vec1[1] = max(nums[0], nums[1]);
		
		vec2[1] = nums[1];
		vec2[2] = max(nums[1], nums[2]);

		for (int i = 2; i < nums.size() - 1; i++) {
			vec1[i] = max(vec1[i - 1], vec1[i - 2] + nums[i]);
		}

		for (int i = 3; i < nums.size(); i++) {
			vec2[i] = max(vec2[i - 1], vec2[i - 2] + nums[i]);
		}

		return max(vec1[leng - 2], vec2[leng - 1]);
	}
};


發佈了42 篇原創文章 · 獲贊 0 · 訪問量 3511
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章