Leetcode 198 House Robber

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

离散的问题求最大值,首先应该想到用DP。例如 nums = [2, 3, 1, 5, 7, 8]

dp[0] = 2, dp[1] = max(nums[0], nums[1]) 这两个点需要单独操作。 dp[i]的值取决于[i]这一家是不是要偷。如果不偷的话,dp[i] = dp[i-1]。如果偷的话,[i-1]这一家就不能偷,所以 dp[i] = dp[i-2] + nums[i]。所以dp[i] = max(dp[i-1], dp[i-2]+nums[i])。

 1     def rob(self, nums):
 2         """
 3         :type nums: List[int]
 4         :rtype: int
 5         """
 6         if not nums:
 7             return 0
 8         n = len(nums)
 9         if n == 1:
10             return nums[0]
11         if n == 2:
12             return max(nums[0], nums[1])
13         
14         dp = [0]*n
15         dp[0] = nums[0]
16         dp[1] = max(nums[1], nums[0])
17         
18         for i in range(2, n):
19             dp[i] = max(dp[i-2]+nums[i], dp[i-1])
20         
21         return dp[-1]

本质上并不需要保存dp list中的所有值,只需要保存两个,分别对应even and odd position。 这样的话可以写成:

 1     def rob(self, nums):
 2         """
 3         :type nums: List[int]
 4         :rtype: int
 5         """
 6         a, b = 0, 0
 7         n = len(nums)
 8         
 9         for i in range(n):
10             if i % 2 == 0:
11                 a += nums[i]
12                 a = max(b, a)
13             else:
14                 b += nums[i]
15                 b = max(a, b)
16         
17         return max(a, b)

 

以上是关于Leetcode 198 House Robber的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 198. House Robber 打家劫舍(中等)

LeetCode 198. House Robber

Leetcode 198 House Robber

[leetcode-198-House Robber]

leetcode 198. House Robber

[LeetCode] 198. House Robber