LeetCode學習篇十四——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.

難度:easy 通過率:26.8%

理解了這道題的題意,狀態轉移方程就很容易想出來了,利用count數組記錄偷取前i家的財產總額,如果偷取第i家,則加上count[i-2],和偷取前i-1家的財產總額比較,取較大值。這裏有個需要注意的地方,一開始忘記判斷特殊情況當數組大小爲0或1時,所以一直導致RTE。
代碼實現如下,時間複雜度:O(n)

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size() == 0) return 0;
        if(nums.size() == 1) return nums[0];
        vector<int> count(nums.size(),0);
        count[0] = nums[0];
        count[1] = max(nums[0],nums[1]);
        for(int i = 2; i < nums.size(); i++) {
            count[i] = max(count[i-2]+nums[i], count[i-1]);
        }
        return count[nums.size()-1];
    }
};
發佈了37 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章