[leetcode]: 198. House Robber

来源:互联网 发布:aspen软件安装包 编辑:程序博客网 时间:2024/06/05 17:13

1.题目

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.

专业抢劫犯,给你一个数组表示一条街上住户的价值,不能抢劫相邻的两家住户,请问最多能抢劫多少钱。

2.分析

动态规划。相当于01背包问题,拿or不拿,但有相邻限制

状态转移方程:
dp[i]=max(dp[i-2]+nums[i], dp[i-1])
dp[i-2]+nums[i]–抢劫i
dp[i-1]–不抢劫i

3.分析

def rob(self, nums):    if not nums:        return 0    if(len(nums)<2):        return nums[0]    dp=[0 for i in nums]    dp[0]=nums[0]    dp[1]=max(nums[0],nums[1])    for i in range(2,len(nums)):        dp[i]=max(dp[i-2]+nums[i],dp[i-1])    return dp[-1]