Leetcode 198. House Robber I II III

29 篇文章 0 订阅
22 篇文章 0 订阅

Leetcode 198. House Robber I

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.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

解题思路:这道题的本质相当于在一列数组中取出一个或多个不相邻数,使其和最大。那么对于这类求极值的问题首先考虑动态规划 Dynamic Programming 来解,维护一个一位数组 dp,其中 dp[i] 表示 [0, i] 区间可以抢夺的最大值,对当前i来说,有抢和不抢两种互斥的选择,不抢即为 dp[i-1](等价于去掉 nums[i] 只抢 [0, i-1] 区间最大值),抢即为 dp[i-2] + nums[i](等价于去掉 nums[i-1])。再举一个简单的例子来说明一下吧,比如说 nums为{3, 2, 1, 5},那么来看 dp 数组应该是什么样的,首先 dp[0]=3 没啥疑问,再看 dp[1] 是多少呢,由于3比2大,所以抢第一个房子的3,当前房子的2不抢,则dp[1]=3,那么再来看 dp[2],由于不能抢相邻的,所以可以用再前面的一个的 dp 值加上当前的房间值,和当前房间的前面一个 dp 值比较,取较大值当做当前 dp 值,这样就可以得到状态转移方程 dp[i] = max(num[i] + dp[i - 2], dp[i - 1]), 且需要初始化 dp[0] 和 dp[1],其中 dp[0] 即为 num[0],dp[1] 此时应该为 max(num[0], num[1]),代码如下:


class Solution {
public:
    int rob(vector<int>& nums)
    {
        if(nums.size() <= 1)
            return nums.empty()? 0:nums[0];
        
        int len = nums.size();
        vector<int> dp(len, -1);
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);

        for(int i = 2; i< len; i++)
        {
            dp[i] = max(dp[i-2] + nums[i], dp[i-1]);
        }
        
        return dp[len-1];
    }
    

};

解题思路二:使用两个变量 rob 和 notRob,其中 rob 表示抢当前的房子,notRob 表示不抢当前的房子,那么在遍历的过程中,先用两个变量 preRob 和 preNotRob 来分别记录更新之前的值,由于 rob 是要抢当前的房子,那么前一个房子一定不能抢,所以使用 preNotRob 加上当前的数字赋给 rob,然后 notRob 表示不能抢当前的房子,那么之前的房子就可以抢也可以不抢,所以将 preRob 和 preNotRob 中的较大值赋给 notRob,参见代码如下:

class Solution {
public:
    int rob(vector<int>& nums)
    {
        if(nums.size() <= 1)
            return nums.empty()? 0:nums[0];
        
        int noRob = 0;
        int rob = 0;
        int len = nums.size();
        for(int i = 0; i< len; i++)
        {
            int preNoRob = noRob;
            int preRob = rob;
            rob = preNoRob + nums[i];
            noRob = max(preRob, preNoRob);
        }
        
        return max(rob, noRob);
    }
};

 213. House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.

Example 1:

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.

Example 2:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

解题思路一:

现在房子排成了一个圆圈,则如果抢了第一家,就不能抢最后一家,因为首尾相连了,所以第一家和最后一家只能抢其中的一家,或者都不抢,那这里变通一下,如果把第一家和最后一家分别去掉,各算一遍能抢的最大值,然后比较两个值取其中较大的一个即为所求。那只需参考之前的 House Robber 中的解题方法,然后调用两边取较大值,代码如下:

class Solution {
public:
    int rob(vector<int>& nums) 
    {
        if(nums.size() <= 1)
            return nums.empty()? 0:nums[0];
        
        return max(rob(nums, 0, nums.size()-1), rob(nums, 1, nums.size()));
    }
    
    int rob(vector<int>& nums,int start, int end) 
    {
        if(end - start <= 1)
            return nums[start];
        
        vector<int> dp(end, 0);
        dp[start] = nums[start];
        dp[start + 1] = max(nums[start], nums[start + 1]);
        for(int i = start + 2; i< end; i++)
        {
            dp[i] = max(dp[i-2] + nums[i], dp[i-1]);
        }
        
        return dp[end-1];
    }
};

解题思路二:我们也可以使用两个变量来代替整个 DP 数组,讲解与之前的帖子 House Robber 相同,分别维护两个变量 robEven 和 robOdd,顾名思义,robEven 就是要抢偶数位置的房子,robOdd 就是要抢奇数位置的房子。所以在遍历房子数组时,如果是偶数位置,那么 robEven 就要加上当前数字,然后和 robOdd 比较,取较大的来更新 robEven。这里就看出来了,robEven 组成的值并不是只由偶数位置的数字,只是当前要抢偶数位置而已。同理,当奇数位置时,robOdd 加上当前数字和 robEven 比较,取较大值来更新 robOdd,这种按奇偶分别来更新的方法,可以保证组成最大和的数字不相邻,最后别忘了在 robEven 和 robOdd 种取较大值返回,代码如下:

class Solution {
public:
    int rob(vector<int>& nums) 
    {
        if(nums.size() <= 1)
            return nums.empty()? 0:nums[0];
        
        return max(rob(nums, 0, nums.size()-1), rob(nums, 1, nums.size()));
    }
    
    int rob(vector<int>& nums,int start, int end) 
    {
        if(end - start <= 1)
            return nums[start];
        
        int even =0;
        int odd = 0;
        for(int i = start ; i< end; i++)
        {
            if(i % 2 == 0)
            {
                even = max(nums[i] + even, odd);
            }
            else
            {
                odd = max(nums[i] + odd, even);
            }
        }
        
        return max(even, odd);
    }
};

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:

Input: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

Output: 7 
Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

Input: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

Output: 9
Explanation: Maximum amount of money the thief can rob = 4 + 5 = 9.

解题思路:此题可以利用回溯法来做,因为当前的计算需要依赖之前的结果,那么对于某一个节点,如果其左子节点存在,通过递归调用函数,算出不包含左子节点返回的值,同理,如果右子节点存在,算出不包含右子节点返回的值,那么此节点的最大值可能有两种情况,一种是该节点值加上不包含左子节点和右子节点的返回值之和,另一种是左右子节点返回值之和不包含当期节点值,取两者的较大值返回即可,但是这种方法无法通过 OJ,超时了,所以必须优化这种方法,这种方法重复计算了很多地方,比如要完成一个节点的计算,就得一直找左右子节点计算,可以把已经算过的节点用 HashMap 保存起来,以后递归调用的时候,现在 HashMap 里找,如果存在直接返回,如果不存在,等计算出来后,保存到 HashMap 中再返回,这样方便以后再调用,参见代码如下:

/**
 * 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) 
    {
        unordered_map<TreeNode*, int> map;
        return dfs(root, map);
    }
    
    int dfs(TreeNode* root, unordered_map<TreeNode*, int> &map)
    {
        if(root == NULL )
            return 0;
        
        if(map.count(root))
            return map[root];
        
        int val = 0;
        if(root->left)
        {
            val += dfs(root->left->left, map) + dfs(root->left->right, map);
        }
        
        if(root->right)
        {
            val += dfs(root->right->left, map) + dfs(root->right->right, map);
        }
        
        val = max(val + root->val, dfs(root->right, map) + dfs(root->left, map));
        map[root] = val;
        
        return val;
    }
};

 

[LeetCode] 198. House Robber 打家劫舍

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值