V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hakunamatata11
V2EX  ›  推广

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

  •  
  •   hakunamatata11 · 2020-05-29 16:43:37 +08:00 · 685 次点击
    这是一个创建于 1495 天前的主题,其中的信息可能已经有所发展或是发生改变。

    [题目描述]

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

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

    在线评测地址:

    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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2914 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 13:52 · PVG 21:52 · LAX 06:52 · JFK 09:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.