LeetCode動態規劃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.


思路點撥

遞歸思想:
搶劫從編號爲cur房子開始,到end結束,所獲得的利益爲:
a)在搶劫第cur房子時,int robed=nums[cur]+rob(cur+2,end),
b) 不搶劫cur房子時,int nonRobed=rob(cur+1,end)
c)返回max(robed,nonRobed),該值作爲 搶劫起始編號爲cur,結束爲end的獲得的最大利益。


c++代碼實現

class Solution {
public:
    int recurse(vector<int>& table, vector<int>& nums, int cur, int end)
    {
        if (cur> end)
        {
            return 0;
        }

        // 對於table中曾經通過遞歸確定了的值,不再判斷是否rob
        if (-1 != table[cur])
        {
            return table[cur];
        }

        // 如果是rob,就把當前值加上 以cur+2開始的新的nums用來遞歸判斷得到的最大值 作爲rob時得到的最大值
        int robed = nums[cur] + recurse(table, nums, cur + 2, end);

        // 如果是rob,就把 以cur+1開始的新的nums用來遞歸判斷得到的最大值 作爲沒rob時得到的最大值
        int nonRobed = recurse(table, nums, cur + 1, end);

        // 把2種情況對應的最大值中較大的一個作爲 “強盜從當前house一直到street末尾的house可獲得的最大值”
        table[cur] = (robed > nonRobed) ? robed: nonRobed;

        return table[cur];
    }

    int rob(vector<int>& nums) {
        if (nums.empty())
        {
            return 0;
        }
        int len = nums.size();
        if (1 == len)
        {
            return nums[0];
        }

        // 創建一個與house數量一致的table,table[i]表示從下標爲i的house開始到最後一個house強盜可獲得的最大財富值,初始化爲-1,表示table[i]還未計算
        vector<int> table(len, -1);

        // 遞歸判斷每個table[i], 最後強盜所能獲得的最大財富值就是table[0] 
        return recurse(table, nums, 0, len -1);
    }
};
發佈了13 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章