Skip to content

Commit ee4b65f

Browse files
committed
打劫房屋 II
1 parent eaff977 commit ee4b65f

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

house_robber_ii.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# -*- coding: utf-8 -*-
2+
3+
class Solution:
4+
# @param nums: A list of non-negative integers.
5+
# return: an integer
6+
def houseRobber2(self, nums):
7+
# write your code here
8+
'''
9+
与打劫房屋相比:
10+
1. 如果我抢了第1间,最后一间就不能抢。
11+
2. 如果第一间不抢,就可以抢最后一间。
12+
'''
13+
if not nums:
14+
return 0
15+
elif len(nums) == 1:
16+
return nums[0]
17+
elif len(nums) == 2:
18+
return max(nums[0], nums[1])
19+
else:
20+
ret_1, ret_2 = 0, 0
21+
# 场景1
22+
caches = nums[:]
23+
caches[1] = max(caches[0], caches[1])
24+
for i in xrange(2, len(nums) - 1):
25+
caches[i] = max(caches[i] + caches[i - 2], caches[i - 1])
26+
ret_1 = caches[-2]
27+
caches = nums[:]
28+
caches[0] = 0
29+
for i in xrange(2, len(nums)):
30+
caches[i] = max(caches[i] + caches[i - 2], caches[i - 1])
31+
ret_2 = caches[-1]
32+
return max(ret_1, ret_2)

0 commit comments

Comments
 (0)