198. House Robber
打家劫舍
Last updated
Was this helpful?
打家劫舍
Last updated
Was this helpful?
英文网站:
中文网站:
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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums
representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Example 2:
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 400
这就是状态转移方程。根据状态转移方程,很容易就可以写出代码。
这段代码的时间复杂度是 O(n),空间复杂度也是 O(n)。
通过上面这段代码,可以发现,其实我们只要维护dp[i]、dp[i-1] 以及 dp[i-2] 这三个数就可以了,没必要维护一个数组,因为我们只关心小偷分别在当前人家、上一户人家以及上上户人家的最大总收入,所以上面这段代码可以优化成下面这样:
经过优化,我们的代码空间复杂度变成了 O(1)。
本题可以采用动态规划来解决,我们用表示第 i 户人家所拥有的钱数, 表示该小偷在前 i 户人家,能够偷到的最大总钱数。假设当这个小偷来到第 i+1 户人家的门前时,已经知道了前面 的取值,由于他不能连续偷相邻的两户人家,所以如果他偷了第 i+1 户人家,就不能偷第 i 户人家,那么他此时的总收入应该是 ,我们将这个数记为 t。如果 ,那么 ,如果 ,那么他还不如不偷第 i+1 户人家,维持在前 i 户人家得到的收入,也就是 ,这种情况下, 。所以, 的取值取决于 t 和 的大小,即: ,对这个式子做一下变形,可以得到 :
、