213. 打家劫舍 II
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/713c1ef3ebc8610b61962fbe373a594c.png)
class Solution {
public:
int rodUnidirection(vector<int> nums, int startIndex, int endIndex){
vector<int> dp(endIndex-startIndex+2, 0);
dp[startIndex] = nums[startIndex];
for(int dpIndex = startIndex + 1; dpIndex <= endIndex; dpIndex++){
if(dpIndex == 1){
dp[1] = max(nums[startIndex], nums[startIndex + 1]);
}
else{
dp[dpIndex] = max((dp[dpIndex - 2] + nums[dpIndex]), dp[dpIndex - 1]);
}
}
return dp[endIndex];
}
int rob(vector<int>& nums) {
int numsSize = nums.size();
if(numsSize == 0){
return 0;
}
if(numsSize == 1){
return nums[0];
}
int max0ToN_2 = rodUnidirection(nums, 0, numsSize - 2);
int max1ToN_1 = rodUnidirection(nums, 1, numsSize - 1);
return max(max0ToN_2, max1ToN_1);
}
};
class Solution {
public:
int rodUnidirection(vector<int> nums, int startIndex, int endIndex){
vector<int> dp(endIndex-startIndex+2, 0);
dp[startIndex] = nums[startIndex];
for(int dpIndex = startIndex + 1; dpIndex <= endIndex; dpIndex++){
if(dpIndex == 1){
dp[1] = max(nums[startIndex], nums[startIndex + 1]);
}
else{
dp[dpIndex] = max((dp[dpIndex - 2] + nums[dpIndex]), dp[dpIndex - 1]);
}
}
return dp[endIndex];
}
int rob(vector<int>& nums) {
int numsSize = nums.size();
if(numsSize == 0){
return 0;
}
if(numsSize == 1){
return nums[0];
}
int max0ToN_2 = rodUnidirection(nums, 0, numsSize - 2);
int max1ToN_1 = rodUnidirection(nums, 1, numsSize - 1);
return max(max0ToN_2, max1ToN_1);
}
};