LeetCode-198 & 213:House Robber (房屋抢劫)

题目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.

问题解析:

每个房间里都有不同数量的财物,给出能抢劫的最大财物数。这里的唯一限制是不能同时对相邻的房间进行抢劫。

链接:

思路标签:

算法:DP

解答:

  • 明显的动态规划问题:从左到右抢劫,对于每间房子,其当前最大抢劫财物数为:到前前个房子的最大财物数+当前屋子财物数 or 到前一个屋的最大财物数,选取二者的最大值;也就是说要么抢当前屋子,要么不抢。
  • 每次都保存到前一个屋子的最大抢劫财物数和到当前屋子的抢劫财务数;
  • 使用两个量来保存即可,无需使用数组来保存。
class Solution {
public:
    int rob(vector<int>& nums) {
        int length = nums.size();
        if(length == 0) return 0;
        if(length == 1) return nums[0];

        int previous = nums[0];
        int current = max(nums[0], nums[1]);
        for(int i=2; i<length; ++i){
            int temp = current;
            current = max(previous+nums[i], current);
            previous = temp;
        }

        return current;
    }
};

题目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.

问题解析:

题目在198的基础上增加条件:社区是一个环形,第一个房子和最后一个房子相邻。

链接:

思路标签:

算法:DP

解答:

  • 可以利用上一题的思想来求解;
  • 因为对于n个房间:0~n-1,第一个房间和第二个房间相连。所以我们可以将整体分为两个子序列,分别计算0~n-21~n-1,选取其中的最大值。
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 - 2), robber(nums, 1, n - 1));
    }
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;
    }
};
发布了200 篇原创文章 · 获赞 740 · 访问量 69万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章