Leetcode House Robber II

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode House Robber II相关的知识,希望对你有一定的参考价值。

 

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

 

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.

 

 

本题和House Robber差不多,分成两种情况来解决。第一家是不是偷了,如果偷了,那么最后一家肯定不能偷。

 

 1 class Solution(object):
 2     def rob(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         if not nums:
 8             return 0
 9         n = len(nums)
10         if n == 1:
11             return nums[0]
12         if n == 2:
13             return max(nums[0], nums[1])
14             
15         dp = [0]* n
16         dp[0] = 0
17         dp[1] = nums[1]
18         
19         for i in range(2,n):
20             dp[i] = max(dp[i-2]+nums[i], dp[i-1])
21         
22         case1 = dp[-1]
23         
24         dp = [0]* (n-1)
25         dp[0] = nums[0]
26         dp[1] = nums[0]
27         
28         for i in range(2,n-1):
29             dp[i] = max(dp[i-2]+nums[i], dp[i-1])
30         
31         case2 = dp[-1]
32         
33         return max(case1, case2)
34         
View Code

 

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

[LeetCode]House Robber II

leetcode No213. House Robber II

LeetCode 213. House Robber II

[动态规划] leetcode 213 House Robber II

leetcode 213. House Robber II 抢劫房子II---------- java

Leetcode House Robber II