Leetcode-213 House Robber II(打家劫舍 II)

 1 #define maxn 1000000
 2 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 3 #define pb push_back
 4 
 5 class Solution
 6 {
 7     public:
 8         int rob(vector<int>& nums)
 9         {
10             int sz = nums.size();
11             if(sz==0)
12                 return 0;
13             else if(sz==1)
14                 return nums[0];
15             else if(sz==2)
16                 return max(nums[0],nums[1]);
17                 
18             int dp[sz+2] {0};
19             int rnt;
20             
21             dp[2] = nums[2];
22             _for(i,3,sz-1)
23             {
24                 if(i>3)
25                     dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
26                 else
27                     dp[i] = max(nums[i],dp[i-1]);
28             }
29             rnt = nums[0]+dp[sz-2];
30             
31             memset(dp,0,sizeof(dp));
32             dp[1] = nums[1];
33             _for(i,2,sz-2)
34             {
35                 if(i>2)
36                     dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
37                 else
38                     dp[i] = max(nums[i],dp[i-1]);
39             }
40             rnt = max(rnt,nums[sz-1]+dp[sz-3]);
41             
42             memset(dp,0,sizeof(dp));
43             dp[1] = nums[1];
44             _for(i,2,sz-1)
45             {
46                 if(i>2)
47                     dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
48                 else
49                     dp[i] = max(nums[i],dp[i-1]);
50             }
51             rnt = max(rnt,dp[sz-2]);
52             
53             return rnt;
54         }
55 };

 

posted @ 2019-02-14 09:56  Asurudo  阅读(303)  评论(0编辑  收藏  举报