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.
这题题意给的很有意思,说是抢劫的最多的钱的数目。 实际上是求数组中避免取相邻元素的最大和。
这题定义子状态非常关键,如果只是定义为抢劫数组第i个元素的能得到最大值,则不仅需要扫描一遍数组,还需要不断更新最大值。另外一个定义直接是数组的前i 个元素可以取到的最大和,即不一定包含当前元素,这样也避免再取一次最大值。转换方程为f[i] = max(f[i-1], f[i-2]+nums[i]). f[i-1]也不一定包含nums[i-1]元素,为何只在f[i-2]上加呢。因为如果f[i-1]不包含nums[i-1],则 f[i-1] = f[i-2]。这题可以进行空间优化,只需要保存前面两个状态。
一个是直接取前两个状态,每次计算,交替更新:
代码如下:
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 if len(nums) < 2: return nums[0] f1 = nums[0] f2 = max(nums[0], nums[1]) for n in nums[2:]: res = max(f1 + n, f2) f1 = f2 f2 = res return f2
另外一个是利用%2的策略,取一个长度为2的数组。即跟前面几个状态有关,则取几个,后面每次计算取值也是将index%2,代码如下:
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 if len(nums) < 2: return nums[0] #f[i]: max money can get when reach A[i] res = [nums[0], max(nums[0], nums[1])] for i in xrange(2, len(nums)): res[i%2] = max(res[(i-2)%2] + nums[i], res[(i-1)%2]) return res[(len(nums)-1)%2]
posted on 2016-06-13 10:13 Sheryl Wang 阅读(144) 评论(0) 编辑 收藏 举报