打家劫舍1
class Solution {
public:
int rob(vector<int>& nums) {
int n = nums.size();
if(n==0) return 0;
if(n==1) return nums[0];
vector<int> dp(n,0);
dp[0] = nums[0];
dp[1] = max(nums[0],nums[1]);
for(int i=2;i<n;i++){
dp[i] = max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[n-1];
}
};
class Solution {
public:
int rob(vector<int>& nums) {
int pre2 = 0, pre1 = 0;
for (int i = 0; i < nums.length; i++) {
int cur = max(pre2 + nums[i], pre1);
pre2 = pre1;
pre1 = cur;
}
return pre1;
}
};
打家劫舍2
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n==0) return 0;
if(n==1) return nums[0];
return max(robCri(nums,0,n-2),robCri(nums,1,n-1));
}
int robCri(vector<int>& nums,int start,int end){
int pre=0,cur=0;
for(int i=start;i<=end;i++){
int temp = max(pre+nums[i],cur);
pre = cur;
cur = temp;
}
return cur;
}
};
打家劫舍3
class Solution {
public:
int rob(TreeNode* root) {
vector<int> res=dfs(root);
return max(res[0], res[1]);
}
private:
vector<int> dfs(TreeNode* root){
if(root==NULL) return {0,0};
vector<int> res1(2,0);
vector<int> left = dfs(root->left);
vector<int> right=dfs(root->right);
res1[0] = max(left[0],left[1])+max(right[0],right[1]);
res1[1] = root->val + left[0] + right[0];
return res1;
}
};