算法分析與設計課程作業第十七週#1#2

算法分析與設計課程作業第十七週#1#2

這周選了兩道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[i]表示從0到i能搶劫的最高金額。
dp[i] = max(dp[i-1], dp[i-2] + nums[i])

代碼

class Solution {
public:
    int rob(vector<int>& nums) {
        int size = nums.size();
        vector<int> dp(size, 0);
        if(size == 0) return 0;
        dp[0] = nums[0];
        if(size == 1) return dp[0];
        dp[1] = max(nums[0], nums[1]);
        for(int i = 2; i < size; i++){
            dp[i] = max(dp[i-1], dp[i-2] + nums[i]);
        }
        return dp[size-1];
    }
};

213. House Robber II

Note: This is an extension of House Robber.
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.

思路

這道題將街道連成一個環,使第一間房子與最後一間房子不能同時搶,使上題的計算方法失去終止條件,看似困難很多。但其實還是分類討論就好了。總共就兩種分類,就是第一間房選與第一間房不選,就可以退化成用上一題的算法能解決的問題了。

代碼

class Solution {
public:
    int rob(vector<int>& nums) {
        int size = nums.size();
        vector<int> dp(size, 0);
        if(size == 0) return 0;
        dp[0] = nums[0];
        if(size == 1) return dp[0];
        dp[1] = nums[0];
        for(int i = 2; i < size-1; i++){
            dp[i] = max(dp[i-1], dp[i-2] + nums[i]);
        }
        int choosefirst = dp[size-2];
        dp[0] = 0;
        dp[1] = nums[1];
        for(int i = 2; i < size; i++){
            dp[i] = max(dp[i-1], dp[i-2] + nums[i]);
        }
        int chooselast = dp[size-1];
        return max(choosefirst, chooselast);
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章