LeetCode:House Robber
来源:互联网 发布:dota2永恒矩阵 编辑:程序博客网 时间:2024/06/12 00:51
题目: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.
解题思路:本题可以看做求nums数组中不相邻的数字的最大值和。
这是一个动态规划(DP)问题,设一个数组nums:
如果len(nums)=1,那么sum(0)=nums[0]
如果len(nums)=1,那么sum(1)=max(nums[0],nums[1])
如果len(nums)=2,那么sum(2)=max(sum(0)+nums[i],sum(1))
以此类推,sum(k)=max(sum(k-2)+nums[k],sum(k-1))
代码:
class Solution(object): def rob(self,nums): k=len(nums) sum=[0]*k #或者sum=[0 for i in range(k)] if k== 0: return 0 for i in range(k): if i == 0: sum[i]=nums[0] if i ==1: sum[i]=max(nums[0],nums[1]) sum[i]=max(sum[i-2]+nums[i],sum[i-1]) return sum[-1]
0 0
- 【dp】Leetcode House Robber&& House Robber II
- 【leetcode】House Robber && House Robber II
- LeetCode --- House Robber & House Robber II
- LeetCode OJ House Robber
- Leetcode: House Robber
- Leetcode 198: House Robber
- House Robber - LeetCode
- LeetCode 之 House Robber
- leetcode--House Robber
- [leetcode]47 House Robber
- [LeetCode] House Robber
- LeetCode :House Robber
- [leetcode] House Robber
- [leetcode]House Robber
- [LeetCode]198.House Robber
- LeetCode House Robber题解
- leetcode:House Robber
- [LeetCode]House Robber
- cJSON学习笔记(一)
- 党史学者
- Spark Streaming 作业调度流程
- Androin学习笔记十九:7种形式的Android Dialog使用举例
- Xcode6中添加pch文件
- LeetCode:House Robber
- 动态栈
- poj1330 Nearest Common Ancestors (最近公共祖先)
- RDIFramework.NET ━ .NET快速信息化系统开发框架 V3.0 版新增系统参数管理
- 2016百度之星资格赛 B题
- magento 订单order 增加栏目
- R语言基本操作函数(1)变量的基本操作
- 深入分析:Android中app之间的交互(二,使用ComponentName)
- 为早期项目添加Ribbon界面