打家劫舍 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 arearranged 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 tonightwithout alerting the police.

示例1:

  输入: [2,3,2]
  输出: 3
  解释: 你不能先偷窃 1 号房屋(金额 = 2) ,然后偷窃 3号房屋 (金额 = 2), 因为他们是相邻的。

示例 2:

  输入: [1,2,3,1]
  输出: 4
  解释: 你可以先偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。   
       偷窃到的最高金额 = 1 + 3 = 4 。<br /><br /><br /><br />

算法

设计状态f[i][j][k]表示在前i个房屋中第0号房屋偷(j == 1)或不偷(j == 0)的前提下偷(k == 1)与不偷(k == 0)第i号房屋所能偷窃的最高金额。

可得转移方程:

f[i][j][0] = max{f[i - 1][j][0..1]}

f[i][j][1] = f[i - 1][j][0] + money[i]

答案:

max{f[N][0][0..1], f[N][1][0]}

注意边界处理与特殊情况判断,另外可以采用滚动数组优化空间。

时间复杂度:

O(N)

空间复杂度:

O(1)

代码

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