码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 198 House Robber

时间:2016-12-15 07:35:21      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:system   min   elf   ppi   mat   mon   opp   lis   color   

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

标签:system   min   elf   ppi   mat   mon   opp   lis   color   

原文地址:http://www.cnblogs.com/lettuan/p/6181817.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!