198. House Robber

55次阅读

共计 1673 个字符,预计需要花费 5 分钟才能阅读完成。

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.
Example 1:Input: [1,2,3,1]Output: 4Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:Input: [2,7,9,3,1]Output: 12Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
难度:medium
题目:一个专业的盗贼计划抢一条街。每间门店都有一定的现金,但是每两个相邻的店铺都有连接的安全系统,如果在一晚个上同时抢了两个相邻的店铺则会触发警报,则抢劫行动结束。
给出一组非负整数代表每间店铺的现金数,盗贼如何在不触发警报的情况下获得最多的钱。
思路:递归, 问题拆分,求最大盗取金额即为 f(n) = Max(nums[0, n], nums[0, n – 1]), f(n – 1) = Max(nums[0, n -1], nums[0, n – 2],依次递推。可用递归实现。但这种实现会超时。
基于递归相法简化问题,转由迭代实现。
Runtime: 3 ms, faster than 99.40% of Java online submissions for House Robber.
class Solution {
public int rob(int[] nums) {
// nums = null
if (null == nums || nums.length < 1) {
return 0;
}
// only 1 element
if (1 == nums.length) {
return nums[0];
}

// iterate
int prev = 0, next = nums[0], curVal = next;
for (int i = 1; i < nums.length; i++) {
curVal = Math.max(next, nums[i] + prev);
prev = next;
next = curVal;
}

return next;
}
}
Status: Time Limit Exceeded
class Solution {
public int rob(int[] nums) {
if (null == nums || nums.length < 1) {
return 0;
}
if (1 == nums.length) {
return nums[0];
}

return Math.max(rob(nums, 0), rob(nums, 1));
}

public int rob(int[] nums, int begin) {
if (begin + 1 >= nums.length) {
return nums[begin];
}

int sum = nums[begin];
int maxSubSum = 0;
for (int i = begin + 2; i < nums.length; i++) {
maxSubSum = Math.max(rob(nums, i), maxSubSum);
}
sum += maxSubSum;

return sum;
}
}

正文完
 0