题目描述:
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.
题目描述比较长, 大概意思是,你是一个专业的强盗,计划去抢一条街道上的房子。 每个房子里有一定量的钱,但是每相邻的两个房子设有警报,当你同时抢了相邻的房子后,便会触发报警,问,怎么样抢劫,才能抢到最多的钱。而不触发报警。 使用一组整数代表房子里面的钱。
分析: 也就是不能抢相邻的房子, 如你抢了1号房子,接下来选择只能从3号开始,
使用m[i] 表示抢到 i号房子时,能拿到的最大的钱,则:
m[i] = max(m[i-1], d[i]+ m[i-2]) d[i] 代表房子i里面的钱
即,抢第i个房子 为 d[i] + m[i-2] 不抢第i个房子 为m[i-1]
初始化:m[0] = d[0], m[1] = max(d[0], d[1])
由此可以得出代码:
class Solution(object): def rob(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 l = len(nums) if l < 2: return nums[0] m = [0]*l m[0] = nums[0] m[1] = max(nums[0], nums[1]) for i in range(2, l): m[i] = max(m[i-1], nums[i] + m[i-2]) return max(m)