您的位置:首页 > 其它

198. House Robber

2017-11-03 12:22 369 查看

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.

Credits:

Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

你是一个专业的马贼,计划在街上的房子抢劫。 每家都有一定数量的钱,唯一的限制是阻止你们抢劫每一个相邻的房屋,因为相邻的房子有安全系统连接,如果两个相邻的房屋在同一天晚上被抢,它会自动联系报警。

给出一个表示每个房屋的金额的非负整数的列表,确定你今天晚上不被警察发现的情况下可以抢劫的最大金额。

解决思路

利用动态规划,我的思路是:

假如有3家,如果抢了第1家,就不能抢第2家,然后一定抢第3家,这时候比较第2家和第1家、第3家的钱的和的大小。

假如有4家,抢了第1家,第2家不能抢,这时候如果抢第3家,则需要与第二家、第4家的和比较大小,如果是抢第四家,则需要将第1、4家的和与第2、3家的最大值比较大小。

由于例1已经求出第一家、第三家的和与第二家的大小比较结果了,所以这种情况只需要记录前面的比较的最大值tmp,然后记录前面1、2家的最大值e’与第四家的和i,这时候再取tmp与前面1、2家的最大值e’的最大值e,最后一步取i与e的最大值。

(注意前一步的i和e,这就是为什么我们使用tmp在这里存储以前的i时计算e,使O(1)空间)

class Solution {
public int rob(int[] num) {
int i = 0;
int e = 0;
for (int k = 0; k<num.length; k++) {
int tmp = i;
i = num[k] + e;
e = Math.max(tmp, e);
}
return Math.max(i,e);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: