首页 > 其他 > 详细

198. House Robber

时间:2019-02-15 20:48:12      阅读:211      评论:0      收藏:0      [点我收藏+]

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.

Example 1:

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.

Example 2:

Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
             Total amount you can rob = 2 + 9 + 1 = 12.

 

Approach #1: DP + Memory. [C++]

class Solution {
public:
    int rob(vector<int>& nums) {
        int len = nums.size();
        vector<int> memo(len, -1);
        return rob(nums, len-1, memo);
    }
    
private:
    int rob(const vector<int>& nums, int idx, vector<int>& memo) {
        if (idx < 0) return 0;
        if (memo[idx] >= 0) return memo[idx];
        int result = max(rob(nums, idx-2, memo)+nums[idx], rob(nums, idx-1, memo));
        memo[idx] = result;
        return result;
    }
};

  

Approach #2: Iterator + Memory. [C++]

    int rob2(vector<int>& nums) {
        int len = nums.size();
        if (len == 0) return 0;
        
        vector<int> memo(len+1);
        memo[0] = 0;
        memo[1] = nums[0];
        for (int i = 1; i < len; ++i) 
            memo[i+1] = max(memo[i-1] + nums[i], memo[i]);
        
        return memo[len];
    }

  

Approach #3: Iterator. [C++]

    int rob(vector<int>& nums) {
        int len = nums.size();
        if (len == 0) return 0;
        
        int pre1 = 0;
        int pre2 = 0;
        for (int i = 0; i < len; ++i) {
            int temp = pre1;
            pre1 = max(pre2 + nums[i], pre1);
            pre2 = temp;
        }

        return pre1;
    }

  

 

Analysis:

https://leetcode.com/problems/house-robber/discuss/156523/From-good-to-great.-How-to-approach-most-of-DP-problems.

 

198. House Robber

原文:https://www.cnblogs.com/ruruozhenhao/p/10385656.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!