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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章