213. 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.

 这个地方的所有房屋都排成一个圆圈。这意味着第一栋房屋是最后一栋房屋的邻居。

 

思路:首尾算邻居,所以我们分别去掉头,分别去掉尾,然后利用第一问的程序,得到最大偷盗金额。取max.

 

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if(n==0) return 0;
 6         if(n==1) return nums[0];
 7         vector<int> nums1(nums.begin(),nums.end()-1);
 8         vector<int> nums2(nums.begin()+1,nums.end());
 9         int m1 = rob1(nums1);    
10         int m2 = rob1(nums2);
11         return std::max(m1,m2);
12     }
13      int rob1(vector<int>& nums) {
14         int n = nums.size();
15         if(n==0) return 0;
16         if(n==1) return nums[0];
17         if(n==2) return std::max(nums[0],nums[1]);
18         vector<int> dp(n,0);
19         dp[0] = nums[0];
20         dp[1] = std::max(nums[0],nums[1]);
21         for(int i = 2;i<n;i++)
22             dp[i] = std::max(dp[i-1],dp[i-2]+nums[i]);
23         return dp[n-1];
24     }
25 };

 

 

 

 

 

 

 1 class Solution {
 2 public:
 3     int rob(vector<int>& nums) {
 4         int n = nums.size();
 5         if(n==0) return 0;
 6         if(n==1) return nums[0];
 7         int temp = nums[n-1];
 8         nums.pop_back();
 9         int m1 = rob1(nums);
10         
11         nums.push_back(temp);
12         nums.erase(nums.begin());
13         
14         int m2 = rob1(nums);
15         return std::max(m1,m2);
16     }
17      int rob1(vector<int>& nums) {
18         int n = nums.size();
19         if(n==0) return 0;
20         if(n==1) return nums[0];
21         if(n==2) return std::max(nums[0],nums[1]);
22         vector<int> dp(n,0);
23         dp[0] = nums[0];
24         dp[1] = std::max(nums[0],nums[1]);
25         for(int i = 2;i<n;i++)
26             dp[i] = std::max(dp[i-1],dp[i-2]+nums[i]);
27         return dp[n-1];
28     }
29 };

 

posted @ 2019-02-22 15:51  乐乐章  阅读(496)  评论(0编辑  收藏  举报