V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
如果想在 V2EX 获得更好的推广效果,欢迎了解 PRO 会员机制:
https://www.v2ex.com/pro/about
hakunamatata11
V2EX  ›  推广

[leetcode/lintcode 题解] 打劫房屋 · House Robber

  •  
  •   hakunamatata11 · May 29, 2020 · 1013 views
    This topic created in 2162 days ago, the information mentioned may be changed or developed.

    [题目描述]

    假设你是一个专业的窃贼,准备沿着一条街打劫房屋。每个房子都存放着特定金额的钱。你面临的唯一约束条件是:相邻的房子装着相互联系的防盗系统,且 当相邻的两个房子同一天被打劫时,该系统会自动报警

    给定一个非负整数列表,表示每个房子中存放的钱, 算一算,如果今晚去打劫,在不触动报警装置的情况下, 你最多可以得到多少钱 。

    在线评测地址:

    https://www.lintcode.com/problem/house-robber/?utm_source=sc-v2ex-fks0529

    [样例]

    样例 1:

    输入: [3, 8, 4]
    输出: 8
    解释: 仅仅打劫第二个房子
    

    样例 2:

    输入: [5, 2, 1, 3] 
    输出: 8
    解释: 抢第一个和最后一个房子
    

    [题解]

    线性 DP 题目.

    设 dp[i] 表示前 i 家房子最多收益, 答案是 dp[n], 状态转移方程是

    dp[i] = max(dp[i-1], dp[i-2] + A[i-1])

    考虑到 dp[i]的计算只涉及到 dp[i-1]和 dp[i-2], 因此可以 O(1)空间解决.

    public class Solution {
        /**
         * @param A: An array of non-negative integers.
         * return: The maximum amount of money you can rob tonight
         */
        public long houseRobber(int[] A) {
            int n = A.length;
            if (n == 0)
                return 0;
            long []res = new long[n+1];
    
            res[0] = 0;
            res[1] = A[0];
            for (int i = 2; i <= n; i++) {
                res[i] = Math.max(res[i-1], res[i-2] + A[i-1]);
            }
            return res[n];
        }
    }
    
    //////////// 空间复杂度 O(1)版本
    
    public class Solution {
        /**
         * @param A: An array of non-negative integers.
         * return: The maximum amount of money you can rob tonight
         */
        public long houseRobber(int[] A) {
            int n = A.length;
            if (n == 0)
                return 0;
            long []res = new long[2];
    
            res[0] = 0;
            res[1] = A[0];
            for (int i = 2; i <= n; i++) {
                res[i%3] = Math.max(res[(i-1)%2], res[(i-2)%2] + A[i-1]);
            }
            return res[n%2];
        }    
    

    [更多题解参考]

    https://www.jiuzhang.com/solution/house-robber/?utm_source=sc-v2ex-fks0529

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2651 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 03:14 · PVG 11:14 · LAX 20:14 · JFK 23:14
    ♥ Do have faith in what you're doing.