1. 198 打家劫舍
打家劫舍
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if(len == 0)
return 0;
else if(len == 1)
return nums[0];
else if(len == 2)
return max(nums[0], nums[1]);
int dp[len][2];
dp[0][0] = 0, dp[0][1] = nums[0];
for(int i = 1; i < len; ++i)
{
dp[i][0] = dp[i - 1][1];
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + nums[i]);
}
return dp[len - 1][1];
}
};
2. 213 打家劫舍 II
213 打家劫舍 II
class Solution {
public:
int rob(vector<int>& nums) {
int len = nums.size();
if(len == 0)
return 0;
else if(len == 1)
return nums[0];
else if(len == 2)
return max(nums[0], nums[1]);
int dp[len][2];
dp[0][0] = 0, dp[0][1] = nums[0];
for(int i = 1; i < (len - 1); ++i)
{
dp[i][0] = dp[i - 1][1];
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + nums[i]);
}
int dpp[len][2];
dpp[1][0] = 0, dpp[1][1] = nums[1];
for(int i = 2; i < len; ++i)
{
dpp[i][0] = dpp[i - 1][1];
dpp[i][1] = max(dpp[i - 1][1], dpp[i - 1][0] + nums[i]);
}
return max(dp[len - 2][1], dpp[len - 1][1]);
}
};
3. 337 打家劫舍 III
337 打家劫舍 III
class Solution {
public:
unordered_map<TreeNode*, int> Select;
unordered_map<TreeNode*, int> NoSelect;
void DFS(TreeNode* root)
{
if(root == nullptr)
return;
DFS(root->left);
DFS(root->right);
Select[root] = root->val + NoSelect[root->left] + NoSelect[root->right];
NoSelect[root] = max(Select[root->left], NoSelect[root->left]) + max(Select[root->right], NoSelect[root->right]);
}
int rob(TreeNode* root) {
DFS(root);
return max(Select[root], NoSelect[root]);
}
};
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/5bd39bda3c2df4763cc50dc9bbc31578.png)