198. 打家劫舍
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
vector<int> dp(nums.size(),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];
}
};
213. 打家劫舍 II
class Solution {
public:
int rob(vector<int>& nums) {
if (nums.size() == 0) return 0;
if (nums.size() == 1) return nums[0];
int res1 = rangeRob(nums, 0, nums.size()-1);
int res2 = rangeRob(nums, 1, nums.size());
return max(res1, res2);
}
int rangeRob(vector<int>& nums, int start, int end) {
if (start == end-1 ) return nums[start];
vector<int> dp(nums.size(), 0);
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-1], dp[i-2] + nums[i]);
}
return dp[end-1];
}
};
337. 打家劫舍 III
class Solution {
public:
int rob(TreeNode* root) {
vector<int> res = robTree(root);
return max(res[0], res[1]);
}
vector<int> robTree(TreeNode* root) {
if (root == nullptr) return vector<int>{0,0};
vector<int> left = robTree(root->left);
vector<int> right = robTree(root->right);
int val1 = root->val + left[0] + right[0];
int val2 = max(left[0], left[1]) + max(right[0], right[1]);
return {val2, val1};
}
};