198.打家劫舍
https://leetcode.cn/problems/house-robber/
class Solution {
public:
int rob(vector<int>& nums) {
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 j = 2; j < nums.size(); j++) {
dp[j] = max(dp[j - 1], dp[j - 2] + nums[j]);
}
return dp.back();
}
};
213.打家劫舍II
https://leetcode.cn/problems/house-robber-ii/
class Solution {
public:
int robRange(vector<int>& nums, int start, int end) {
if (end == start) return nums[start];
if (end - start == 1) return max(nums[start], nums[end]);
vector<int> dp(2);
dp[0] = nums[start];
dp[1] = max(nums[start], nums[start + 1]);
int result = dp[1];
for (int i = start + 2; i <= end; i++) {
result = max(dp[1], dp[0] + nums[i]);
dp[0] = dp[1];
dp[1] = result;
}
return result;
}
int rob(vector<int>& nums) {
if (nums.size() == 1) return nums[0];
if (nums.size() == 2) return max(nums[0], nums[1]);
int result1 = robRange(nums, 0, nums.size() - 2);
int result2 = robRange(nums, 1, nums.size() - 1);
return max(result1, result2);
}
};
337.打家劫舍 III
https://leetcode.cn/problems/house-robber-iii/
class Solution {
public:
void traversal(TreeNode* root) {
if (!root) return;
traversal(root->left);
traversal(root->right);
if (!root->left && !root->right) return;
int tmp = 0;
if (root->left) {
tmp += root->left->val;
if (root->left->left) root->val += root->left->left->val;
if (root->left->right) root->val += root->left->right->val;
}
if (root->right){
tmp += root->right->val;
if (root->right->left) root->val += root->right->left->val;
if (root->right->right) root->val += root->right->right->val;
}
root->val = max(root->val, tmp);
}
int rob(TreeNode* root) {
traversal(root);
return root->val;
}
};
class Solution {
public:
vector<int> traversal(TreeNode* cur) {
//vector[0]代表不可偷该节点,vector[1]代表可偷该节点
if (!cur) return vector<int> {0, 0};
vector<int> left = traversal(cur->left);
vector<int> right = traversal(cur->right);
vector<int> result = {0, 0};
//不偷该节点,可以偷左右节点,也可以不偷
result[0] = max(left[0], left[1]) + max(right[0], right[1]);
//偷该节点,就不能偷左右节点
result[1] = cur->val + left[0] + right[0];
return result;
}
int rob(TreeNode* root) {
vector<int> result = traversal(root);
return max(result[0], result[1]);
}
};