Python版本
python
class Solution:
def rob(self, nums: List[int]) -> int:
n = len(nums)
if(n == 1):
return nums[0]
if(n == 2):
return max(nums[0],nums[1])
def robMoney(left:int,right:int)->int:
f1,f2 = nums[left],max(nums[left],nums[left+1])
for i in range(left+2,right+1):
t = f2
f2 = max(f2,f1+nums[i])
f1 = t
return f2
return max(robMoney(0,n-2),robMoney(1,n-1))
Java版本
java
class Solution {
public int robMoney(int[] nums,int left,int right){
int t,f1 = nums[left],f2 = Math.max(nums[left],nums[left+1]);
for(int i = left+2; i <= right; i++){
t = f2;
f2 = Math.max(f2,f1+nums[i]);
f1 = t;
}
return f2;
}
public int rob(int[] nums) {
int n = nums.length;
if(n == 1) return nums[0];
if(n == 2)return Math.max(nums[0],nums[1]);
return Math.max(robMoney(nums,0,n-2),robMoney(nums,1,n-1));
}
}
CPP版本
cpp
class Solution {
public:
int robMoney(vector<int>& nums,int left,int right){
int t,f1 = nums[left],f2 = max(nums[left],nums[left+1]);
for(int i = left+2; i <= right; i++){
t = f2;
f2 = max(f2,f1+nums[i]);
f1 = t;
}
return f2;
}
int rob(vector<int>& nums) {
int n = nums.size();
if(n == 1)return nums[0];
if(n == 2)return max(nums[0],nums[1]);
return max(robMoney(nums,0,n-2),robMoney(nums,1,n-1));
}
};