LeetCode-难题集之House_Robber系列

——House_Robber,这个系列的题的思路也很简单,不过大神的代码就是给力,因此记下留着以后学习参考。

House_Robber

class Solution {
public:
    int rob(vector<int>& nums) {
		nums.insert (nums.begin(),2,0);
		int n = nums.size();
		vector<int> opt(n,0);
		for(int i=2;i<n;++i){
			opt[i]=max(opt[i-1],opt[i-2]+nums[i]);
		}
		return opt[n-1];
    }
};

//大神的代码是我的版本的更简化,学习学习
class Solution {
public:
    int rob(vector<int>& nums) {
        int it1 = 0, it2 = 0;
        for (int i = 0; i < nums.size(); i++) {
            it1 = max(it1 + nums[i], it2);
            swap(it1, it2);
        }
        return it2;
    }
};

House_Robber2

//我去,思路这么简单,我还想了半天
class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size(); 
        if (n < 2) return n ? nums[0] : 0;
        return max(robber(nums, 0, n - 1), robber(nums, 1, n));
    }
private:
    int robber(vector<int>& nums, int l, int r) {
        int pre = 0, cur = 0;
        for (int i = l; i < r; i++) {
            int temp = max(pre + nums[i], cur);
            pre = cur;
            cur = temp;
        }
        return cur;
    }
};

House_Robber3

class Solution {//知道用递归,但是没有想到这么处理,恩,向大神学习。
public:
  /*
      a
     / \
    b   c

  Consider above case, at leaf
  rob_with_root = root_val+max_left_wo_root + max_right_wo_root
  rob_without_root = max(max_left_with_root, max_left_wo_root) +
                     max(max_right_with_root, max_right_wo_root)
  max_rob = std::max(rob_with_root, rob_without_root);
  */

  void dp(TreeNode* root, int& rob_with_root, int& rob_without_root) {
    if (nullptr == root) {
      rob_with_root = 0;
      rob_without_root = 0;
      return;
    }
    int max_left_wo_root=0;
    int max_right_wo_root=0;

    int max_left_with_root=0;
    int max_right_with_root=0;

    dp(root->left, max_left_with_root, max_left_wo_root);
    dp(root->right, max_right_with_root, max_right_wo_root);

    rob_with_root = root->val + max_left_wo_root + max_right_wo_root;
    rob_without_root = std::max(max_left_with_root, max_left_wo_root) +
                       std::max(max_right_with_root, max_right_wo_root);
  }
  int rob(TreeNode* root) {
    int root_val=0;
    int children_val=0;
    dp(root, root_val, children_val);
    return std::max(root_val, children_val);
  }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值