Leetcode - 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.

[分析]

一维动态规划,记num[i]对应的最大安全盗金为safe[i], 递推式为safe[i] = max(safe[i-1], safe[i-2] + num[i])。

实现时仅需一个三元数组,循环使用.

// version1: 思路不够清晰准确,递推式写错但撞大运实现ok,可读性不好的初版
// 后追加注释
public class Solution {
    public int rob(int[] num) {
        if (num == null || num.length == 0) 
            return 0;
        int safe = 0; // num[i-2] 处能获取的最大盗金,num[i-2]本身不一定被盗
        int adj = 0; // num[i-1]能获取的最大盗金,num[i-1]本身不一定被盗
        int curr = 0; // 盗取num[i]所获的最大盗金
        int max = 0; // num[i]处能获取的最大盗金=max(curr, adj)
        for (int i = 0; i < num.length; i++) {
            curr = safe + num[i];
            if (curr > max)
                max = curr;
            safe = adj;
            adj = max;
        }
        return max;
    }
}
// version 2
// 递推式:safe[i] = max(safe[i-1], safe[i-2] + num[i])
// safe[2]表示num[i]处的最多盗金
// safe[1]表示num[i-1],即在与num[i]相邻的前面一户能拿的最大盗金
// safe[0]表示num[i-2]处最大盗金
public class Solution {
     public int rob(int[] num) {
        if (num == null || num.length == 0) 
            return 0;
        int n = num.length;
        if (n == 1)
            return num[0];
        else if (n == 2)
            return num[0] > num[1] ? num[0] : num[1];
        
        int[] safe = {num[0], (num[1] > num[0]? num[1] : num[0]), 0};
        for (int i = 2; i < num.length; i++) {
            safe[2] = Math.max(safe[1], safe[0] + num[i]);
            safe[0] = safe[1];
            safe[1] = safe[2];
        }
        return safe[2];
     }
}

    

 

猜你喜欢

转载自likesky3.iteye.com/blog/2197586