- class Solution {
- public:
- int rob(vector<int>& nums) {
- if (nums.size() == 0) return 0;
- if (nums.size() == 1) return nums[0];
- vector<int> f(nums.size()+10,0);
- f[1]=nums[0];
- f[2]=max(nums[0],nums[1]);
- for(int i=3;i<=nums.size();i++){
- f[i]=max(f[i-2]+nums[i-1],f[i-1]);
- }
- return f[nums.size()];
- }
- };
- class Solution {
- public:
- int rob(vector<int>& nums) {
- if(nums.size()==0) return 0;
- if(nums.size()==1) return nums[0];
- int res1 = robRange(nums,1,nums.size()-1);
- int res2 = robRange(nums,0,nums.size()-2);
- return max(res1,res2);
- }
- int robRange(vector<int>& nums,int st,int ed) {
- if (ed == st) return nums[st];
- vector<int> f(nums.size()+1,0);
- f[st]=nums[st];
- f[st+1]=max(nums[st],nums[st+1]);
- for(int i=st+2;i<=ed;i++){
- f[i]=max(f[i-2]+nums[i],f[i-1]);
- }
- return f[ed];
- }
- };
- class Solution {
- public:
- int rob(TreeNode* root) {
- vector<int> result = robTree(root);
- return max(result[0], result[1]);
- }
- // 长度为2的数组,0:不偷,1:偷
- vector<int> robTree(TreeNode* cur) {
- if (cur == NULL) return vector<int>{0, 0};
- vector<int> left = robTree(cur->left);
- vector<int> right = robTree(cur->right);
- // 偷cur,那么就不能偷左右节点。
- int val1 = cur->val + left[0] + right[0];
- // 不偷cur,那么可以偷也可以不偷左右节点,则取较大的情况
- int val2 = max(left[0], left[1]) + max(right[0], right[1]);
- return {val2, val1};
- }
- };