leetcode(c++)(打家劫舍)
#include <iostream> #include <vector>
#include <unordered_map>
using namespace std; int rob(const vector<int>& nums) { if(nums.empty())return 0; int n = nums.size(); if(n == 1)return nums[0]; vector<int>dp(n+1); dp[0] = 0; dp[1] = nums[0]; for(int i = 2; i < n+1; ++i) { dp[i] = max(dp[i-2] + nums[i-1],dp[i-1]); } return dp[n]; } int rob1(const vector<int>& nums) { if(nums.empty())return 0; int n = nums.size(); vector<int>nums1,nums2; for(int i = 1; i < n;++i) { nums1.push_back(nums[i]); } for(int i = 0; i < n-1;++i) { nums2.push_back(nums[i]); } return max(rob(nums1),rob(nums2)); }
struct TreeNode
{
int val = 0;
TreeNode* left = nullptr;
TreeNode* right = nullptr;
TreeNode(int val_):val(val_){}
};
int rob(TreeNode* root)
{
unordered_map<TreeNode*,int>map;
if(nullptr == root)return 0;
if(map.find(root)!=map.end())return map.at(root);
int robV = root->val;
if(root->left != nullptr)robV+=rob(root->left->left) + rob(root->left->right);
if(root->right != nullptr)robV+=rob(root->right->left) + rob(root->right->right);
int notRob = rob(root->left)+rob(root->right);
int res = max(robV,notRob);
map[root]=res;
return res;
}
vector<int>robSub(TreeNode* root)
{
if(nullptr == root)return {0,0};
vector<int>leftV = robSub(root->left);
vector<int>rightV = robSub(root->right);
int rob = root->val + leftV[0] + rightV[0];
int notRob = max(leftV[0],leftV[1]) + max(rightV[0],rightV[1]);
return {notRob,rob};
}
int rob1(TreeNode* root)
{
if(nullptr == root)return 0;
vector<int>res = robSub(root);
return max(res[0],res[1]);
}
int main() { //LeetCode198 vector<int>houses{1,2,3,1}; cout << rob(houses) << endl; //LeetCode213 vector<int>housesI{7,4,1,9,3,8,6,5}; cout << rob1(housesI) << endl;
//LeetCode337
TreeNode n0(3);
TreeNode n1(2);
TreeNode n2(3);
TreeNode n3(3);
TreeNode n4(1);
n0.left = &n1;
n0.right = &n2;
n1.right = &n3;
n2.right = &n4;
// cout << rob(&n0) << endl;
cout << rob1(&n0) << endl;
return 0; }