Python作业(leetcode 213)

题目描述:

    

Note: This is an extension of House Robber.

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 are arranged 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 tonight without alerting the police.

题目思路:

1.     先不考虑环的情况,即先处理此题的原始版本

2.     求解无环时,问题的关键在于针对某一间房子抢和不抢的选择。

假如要抢第i个, 就不能抢第i+1个;

假如不抢第i个,那么可以选择抢或者不抢第i+1个

很明显,这是一个动态规划问题。

3.     可以设定数组result[],result[i]表示到该房子时最优选择下的金钱数

4.     加上环的条件后,考虑两种情况即可。第一是抢了第一家,不抢最后一家,第二是不抢第一家,即分别计算抢了2-n和抢了1-n-1的情况,取最大值就是结果

动态算法:

       result[i] = max(result[i - 1],  result[i - 2] + nums[i]);

代码如下:

class Solution(object): 
	def rob(self, nums):
		 """ :type nums: List[int] :rtype: int """
		 length=len(nums)
		 if length==0:
			 return 0
		 elif length==1:
			 return nums[0]
		 elif length==2:
			 return max(nums[0],nums[1])
		 return max(self.dp(nums[1:]),self.dp(nums[:-1]))
	def dp(self,nums):
		if len(nums)==2:
			return max(nums[0],nums[1])
		result=[0 for each in nums]
		result[0]=nums[0]
		result[1]=max(nums[0],nums[1])
		for i in range(2,len(nums)):
			result[i]=max(result[i-2]+nums[i],result[i-1])
		return result[len(nums)-1] 

结果如下:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 是一种流行的高级编程语言,因其简洁易读的语法和广泛的应用领域而受到开发者喜爱。LeetCode 是一个在线编程平台,专门用于算法和技术面试的准备,提供了大量的编程题目,包括数据结构、算法、系统设计等,常用于提升程序员的编程能力和解决实际问题的能力。 在 Python 中刷 LeetCode 题目通常涉及以下步骤: 1. **注册账户**:首先在 LeetCode 官网 (https://leetcode.com/) 注册一个账,这样你可以跟踪你的进度和提交的代码。 2. **选择语言**:登录后,在个人主页设置中选择 Python 作为主要编程语言。 3. **学习和理解题目**:阅读题目描述,确保你理解问题的要求和预期输出。题目通常附有输入示例和预期输出,可以帮助你初始化思考。 4. **编写代码**:使用 Python 编写解决方案,LeetCode 提供了一个在线编辑器,支持实时预览和运行结果。 5. **测试和调试**:使用给出的测试用例来测试你的代码,确保它能够正确地处理各种边界条件和特殊情况。 6. **提交答案**:当代码完成后,点击 "Submit" 提交你的解法。LeetCode 会自动运行所有测试用例并显示结果。 7. **学习他人的代码**:如果遇到困难,可以查看社区中的其他优秀解法,学习他人的思路和技术。 8. **反复练习**:刷题不是一次性的事情,通过反复练习和优化,逐渐提高解题速度和代码质量。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值