198. House Robber
题目描述
计划盗窃同一条街道上房子里的钱。不能同时盗窃两个相邻的房间,否则会触发警报。问在不触动警报的情况下最多能拿到多少钱?
例子
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: 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: 12
Explanation: 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.
思想
(DP)
dp[i] 表示截止到第i家偷到的最多钱数。
两种情况:偷了第i家nums[i] + dp[i-2];没偷第i家dp[i-1]
状态方程:dp[i] = max(dp[i-1], dp[i-2] + nums[i])
解法
复杂度:时间O(n),空间O(n)
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
dp = [0] * (n+2)
for i in range(2, n+2):
dp[i] = max(dp[i-1], dp[i-2] + nums[i-2])
return dp[-1]
解法 - 空间优化
复杂度:时间O(n),空间O(1)
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cur = pre = 0
for num in nums:
pre, cur = cur, max(cur, pre + num)
return cur
213. House Robber II
题目描述
计划盗窃同一条环形街道上房子里的钱。不能同时盗窃两个相邻的房间,否则会触发警报。问在不触动警报的情况下最多能拿到多少钱?
例子
Example 1:
Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
because they are adjacent houses.
Example 2:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
思想
由于是环形街道,所以除了考虑相邻两家不能同时偷外,首尾两家也不能同时偷。
(DP - 法1 - 偷不偷第一家?)
两种情况:不偷第一家(不能偷第2家) + 偷第一家(不能偷最后一家),然后类似198. House Robber。
(DP - 法2)
拆分成两种情况:不考虑第一家 + 不考虑最后一家,然后类似198. House Robber。
边界:考虑只有一家的情况
解法1
复杂度:时间O(n),空间O(1)
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
return max(nums[0] + self.helper(nums[2:-1]), self.helper(nums[1:]))
def helper(self, nums):
cur = pre = 0
for num in nums:
pre, cur = cur, max(cur, pre + num)
return cur
解法2
复杂度:时间O(n),空间O(1)
class Solution(object):
def rob(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 1:
return nums[0]
return max(self.helper(nums[1:]), self.helper(nums[:-1]))
def helper(self, nums):
cur = pre = 0
for num in nums:
pre, cur = cur, max(cur, pre + num)
return cur