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

2020-05-29 16:43:37 +08:00
 hakunamatata11

[题目描述]

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

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

在线评测地址:

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

687 次点击
所在节点    推广
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/676758

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX