[leetcode-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.
思路:
对于中间某个房间i,有两种状态,要么偷,要么不偷。
偷得话总的钱就是money[i-2]+nums[i],如果不偷,总的钱就是money[i-1]
于是 money[i] = max{money[i-2]+nums[i],money[i-1]}
很容易写出如下代码:
时间复杂度为O(n),空间复杂度为O(n)。
int rob(vector<int>& nums) {//money[i] = max{money[i-2]+nums[i],money[i-1]}第i个房间有两种可能 //要么偷,要不不偷,偷的话就是money[i-2]+nums[i] 不偷就是,money[i-1] if (nums.empty())return 0; if (nums.size() == 1) return nums[0]; if (nums.size() == 2) return max(nums[0],nums[1]); vector<int>money(nums.size()); money[0] = nums[0]; money[1] = max(nums[0], nums[1]); for (int i = 2; i < nums.size();i++) { money[i] = max(money[i-2]+nums[i],money[i-1]); } return money.back(); }
其实还有时间复杂度为O(1)的方法。。(⊙o⊙)…目前还没有看懂:
For every house k, there are two options: either to rob it (include this house: i) or not rob it (exclude this house: e).
-
Include this house:
i = num[k] + e (money of this house + money robbed excluding the previous house) -
Exclude this house:
e = max(i, e) (max of money robbed including the previous house or money robbed excluding the previous house)
(note that i and e of the previous step, that's why we use tmp here to store the previous i when calculating e, to make O(1) space)
Here is the code:
public 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); } }
参考:
https://discuss.leetcode.com/topic/11354/dp-o-n-time-o-1-space-with-easy-to-understand-explanation
http://qiaopeng688.blog.51cto.com/3572484/1844956