Leetcode 198 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.

离散的问题求最大值,首先应该想到用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)

 

转载于:https://www.cnblogs.com/lettuan/p/6181817.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值