今日任务
198. 打家劫舍
- 题目链接:
- 题目描述:
Code
class Solution {
public:
int rob(vector<int>& nums) {
int f0, f1;
f0 = f1 = 0;
for(int i = 0; i < nums.size(); i++){
int new_f = max(f1, f0 + nums[i]);
f0 = f1;
f1 = new_f;
}
return f1;
}
};
213.打家劫舍II
- 题目链接: https://leetcode.cn/problems/house-robber-ii/
- 题目描述:
Code
class Solution {
public:
int rob(vector<int>& nums) {
return max(nums[0] + robWithoutCircle(2, nums.size() - 2, nums), robWithoutCircle(1, nums.size() - 1, nums));
}
int robWithoutCircle(int begin, int end, vector<int> & nums){
int f0, f1;
f0 = f1 = 0;
for(int i = begin; i <= end; i++){
int new_f = max(f1, f0 + nums[i]);
f0 = f1;
f1 =new_f;
}
return f1;
}
};
337.打家劫舍III
- 题目链接: https://leetcode.cn/problems/house-robber-iii/description/
- 题目描述:
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
map<int, int> levelSumMap;
public:
int rob(TreeNode* root) {
pair<int, int> rst = dfs(root);
return max(rst.first, rst.second);
}
pair<int, int> dfs(TreeNode* node){
if(node == nullptr){
return make_pair(0, 0);
}
pair<int, int> left = dfs(node->left);
pair<int, int> right = dfs(node->right);
int rob = left.second + right.second + node->val;
int not_rob = max(left.first, left.second) + max(right.first, right.second);
return make_pair(rob, not_rob);
}
};
// int rob(TreeNode* root) {
// levelOrder(root, 0);
// int odd = 0;
// int even = 0;
// for(auto & pair : levelSumMap){
// if(pair.first % 2 == 0){
// even += pair.second;
// }else{
// odd += pair.second;
// }
// }
// return max(odd, even);
// }
// void levelOrder(TreeNode * node, int level) {
// if (!node) {
// return;
// }
// queue<pair<TreeNode*, int>> q; // 使用 pair 存储节点和层级
// q.push({node, level});
// while (!q.empty()) {
// auto cur = q.front();
// q.pop();
// TreeNode *currentNode = cur.first;
// int currentLevel = cur.second;
// levelSumMap[currentLevel] += currentNode->val; // 假设 levelSumMap 是你用来存储每层和的映射
// if (currentNode->left) {
// q.push({currentNode->left, currentLevel + 1});
// }
// if (currentNode->right) {
// q.push({currentNode->right, currentLevel + 1});
// }
// }
// }