classSolution{public:introb(vector<int>& nums){if(nums.size()==0)return0;if(nums.size()==1)return nums[0];int first = nums[0];int second =max(nums[1], nums[0]);for(int i =2; i < nums.size(); i++){int tmp =max(first + nums[i], second);
first = second;
second = tmp;}return second;}};
环形打架劫色
classSolution{public:introb(vector<int>& nums){if(nums.size()==0)return0;if(nums.size()==1)return nums[0];if(nums.size()==2)returnmax(nums[0], nums[1]);int a = nums[0];int b =max(nums[0], nums[1]);int c = nums[1];int d =max(nums[1], nums[2]);for(int i =2; i < nums.size()-1; i++){int tmp =max(a+nums[i], b);
a = b;
b = tmp;
tmp =max(c+nums[i+1], d);
c = d;
d = tmp;}returnmax(b, d);}};
树形打家劫舍
pair<int,int>help(TreeNode* root){if(root ==nullptr)returnmake_pair(0,0);auto left =help(root->left);auto right =help(root->right);int second = left.first + right.first;int first =max(second, root->val + left.second + right.second);returnmake_pair(first, second);}introb(TreeNode* root){auto res =help(root);return res.first;}
树形单路径打家劫舍
pair<int,int>help(TreeNode* root,int&res){if(root ==nullptr)returnmake_pair(0,0);auto left =help(root->left, res);auto right =help(root->right, res);int max_val =max(root->val + left.second + right.second, left.first + right.first);
res =max(res, max_val);int second =max(left.first, right.first);int first = root->val +max(left.second, right.second);
first =max(second, first);returnmake_pair(first, second);}introb(TreeNode* root){int res = INT_MIN;help(root, res);return res;}
标准打架劫色class Solution {public: int rob(vector<int>& nums) { if (nums.size() == 0) return 0; if (nums.size() == 1) return nums[0]; int first = nums[0]; int second = max(nums[1], nums[0])