Money Robbing

問題描述
A robber is 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.

思路
類似於0,1揹包問題,但是不同的是相鄰的兩個房子的財產不能拿,因此假設我們已經有了子問題的最優解(在前面的n-1個房子中,每搶劫一個房子我們獲得的最多財產)我們考慮是否拿最後一個房子的財產,分爲兩種情況(1)如果拿了,那麼所有的財產則等於最後一個房子的財產加上n-2個房子中獲得的財產,(2)如果不拿,則總財產就等於n-1房子中獲得的總財產。我們得到如下的遞歸式 OPT(i)=max{OPT(i-2)+Vi,OPT(i-1)}

代碼

class Solution {
public:
    int max(int a, int b){
        return a>b? a:b;
    }
    int rob(vector<int>& nums) {
        int length=nums.size();
        if(length==0) return 0;
        vector<int> ans(length,0);
        ans[0]=nums[0];
        ans[1]=max(nums[0],nums[1]);
        if(length==1) return nums[0];
        if(length==2) return ans[1];

        for(int i=2;i<length;i++)
            ans[i]=max(ans[i-1],ans[i-2]+nums[i]);
        return ans[length-1];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章