LeetCode-难题集之House_Robber系列

来源:互联网 发布:重庆市网络办事大厅 编辑:程序博客网 时间:2024/05/16 00:27

——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
原创粉丝点击