Day48 动态规划part09 198. 打家劫舍 213. 打家劫舍 II 337. 打家劫舍 III
class Solution {
public:int rob(vector<int>& nums) {vector<int> dp(nums.size()); if(nums.size()==0) return 0;if(nums.size()==1) return nums[0];dp[0] = nums[0];dp[1] = max(nums[0],nums[1]);for(int i = 2; i<nums.size();i++){dp[i] = max(dp[i-1],dp[i-2]+nums[i]); }return dp[nums.size()-1];}
};
class Solution {
public:int lineResult(vector<int>& nums,int start,int end){ if(start == end) return nums[start]; vector<int> dp(nums.size());dp[start] = nums[start];dp[start+1] = max(nums[start],nums[start+1]);for(int i = start+2; i<= end;i++){ dp[i] = max(dp[i-2]+nums[i],dp[i-1]);}return dp[end];}int rob(vector<int>& nums) {if (nums.size() == 0) return 0;if (nums.size() == 1) return nums[0]; int result1 = lineResult(nums,0,nums.size()-2);int result2 = lineResult(nums,1,nums.size()-1);return max(result1,result2);}
};
class Solution {
public:vector<int> robTree(TreeNode* cur){if(cur == nullptr) return vector<int> {0,0}; vector<int> leftdp = robTree(cur->left); vector<int> rightdp = robTree(cur->right);int val1 = max(leftdp[0],leftdp[1]) + max(rightdp[0],rightdp[1]); int val2 = cur->val + leftdp[0] + rightdp[0];return {val1,val2};}int rob(TreeNode* root) {vector<int> dproot = robTree(root);return max(dproot[0],dproot[1]);}
};