zoukankan      html  css  js  c++  java
  • 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.

    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.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    最小生成树(卡鲁斯卡尔)
    最小生成树(kruskal模版 Prim模板)
    hdu1247(Hat’s Words)
    hdu1671Phone List(字典树)
    hdu1305Immediate Decodability(字典树)
    hdu1251(统计难题)
    oj1500(Message Flood)字典树
    oj2892(字典树)
    数论公式
    2504(多项式求和)
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10385656.html
Copyright © 2011-2022 走看看