LeetCode - 198/213/337 - House Robber

36 篇文章 0 订阅
30 篇文章 0 订阅

198. House Robber

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.


一个小偷抢劫一排直线上的n户人家,相邻的两家不能同时抢劫,问最多能抢多少钱。

dp[i][0]表示没有抢劫当前房子的最大money,dp[i][1]表示抢劫当前房子的最大money,那么有

dp[i][0] = max(dp[i-1][0], dp[i-1][1])

dp[i][1] = dp[i-1][0] + nums[i-1]

实际上只需要两个变量就好惹。时间复杂度O(n),空间复杂度O(1)

class Solution {
public:
    int rob(vector<int>& nums) {
        int preN = 0;
        int preY = 0;
        for (int i = 0; i < nums.size(); ++i) {
            int x = preN;
            preN = max(preN, preY);
            preY = x + nums[i];
        }
        return max(preN, preY);
    }
};




213. House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.


基本题意同上,不过这题的房子呈一个环。

基本思路也同上一题一样,不过由于nums[0]和nums[n-1]不能同时出现,所以我们分开求解这两部分。计算抢劫nums[0]到nums[n-2]的值,再计算抢劫nums[1]到nums[n-1]的值,返回二者最大值即可。

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        if (n < 2) return n ? nums[0] : 0;
        return max(solve(nums, 0, n - 2), solve(nums, 1, n - 1));
    }
    int solve(vector<int>& nums, int st, int en) {
        int preN = 0;
        int preY = 0;
        for (int i = st; i <= en; ++i) {
            int x = preN;
            preN = max(preN, preY);
            preY = x + nums[i];
        }
        return max(preN, preY);
    }
};




337. House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3
    / \
   2   3
    \   \ 
     3   1
Maximum amount of money the thief can rob =  3  +  3  +  1  =  7 .

Example 2:

     3
    / \
   4   5
  / \   \ 
 1   3   1
Maximum amount of money the thief can rob =  4  +  5  =  9 .


嗯,进化版的小偷,怕不是要分个身。

这题,根据评论区的思路一步一步进化代码。

首先,我们可以我们定义一个函数rob(root),它将返回最大量的钱。从树根的角度来看,最终只有两个场景:根被盗或不是。如果是这样,由于“我们不能抢两个直接连接的房屋”的限制,可用的下一级子树将是四个“孙子子树”(root.left.left,root.left.right ,root.right.left,root.right.right)。但是,如果root没有被抢,下一级可用的子树只是两个“子树”(root.left,root.right)。我们只需要选择产生更大金额的场景。

public int rob(TreeNode root) {
    if (root == null) return 0;
    
    int val = 0;
    
    if (root.left != null) {
        val += rob(root.left.left) + rob(root.left.right);
    }
    
    if (root.right != null) {
        val += rob(root.right.left) + rob(root.right.right);
    }
    
    return Math.max(val + root.val, rob(root.left) + rob(root.right));
}

在第一步中,我们只考虑了“最佳子结构”的方面,但是对于子问题的重叠可能性很少。 例如,要获取rob(root),我们需要rob(root.left.left),rob(root.left.right); 但是要获取rob(root.left),我们也需要rob(root.left.left),rob(root.left.right)。 上述的方案反复计算这些子问题,导致时间性能不佳。在这里实现DP的简单方法是使用哈希映射来记录访问子树的结果。

public int rob(TreeNode root) {
    return robSub(root, new HashMap<>());
}

private int robSub(TreeNode root, Map<TreeNode, Integer> map) {
    if (root == null) return 0;
    if (map.containsKey(root)) return map.get(root);
    
    int val = 0;
    
    if (root.left != null) {
        val += robSub(root.left.left, map) + robSub(root.left.right, map);
    }
    
    if (root.right != null) {
        val += robSub(root.right.left, map) + robSub(root.right.right, map);
    }
    
    val = Math.max(val + root.val, robSub(root.left, map) + robSub(root.right, map));
    map.put(root, val);
    
    return val;
}

我们将rob(root)关联到rob(root.left)和rob(root.right)。对于rob(root)的第一个元素,我们只需要总结rob(root.left)和rob(root.right)的较大元素,因为root没有被抢,我们可以自由地抢夺它的左右子树。然而,对于rob(root)的第二个元素,我们只需要分别添加rob(root.left)和rob(root.right)的第一个元素,加上从根本身抢夺的值,因为在这种情况下它保证我们无法抢夺root.left和root.right的节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int rob(TreeNode* root) {
        if (!root) return 0;
        vector<int> ans = solve(root);
        return max(ans[0], ans[1]);
    }
    vector<int> solve(TreeNode* root) {
        if (!root) {
            vector<int> ans(2, 0);
            return ans;
        }
        
        vector<int> le = solve(root->left);
        vector<int> ri = solve(root->right);
        
        vector<int> ans(2, 0);
        ans[0] = max(le[0], le[1]) + max(ri[0], ri[1]);
        ans[1] = le[0] + ri[0] + root->val;
        
        return ans;
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值