[leetcode]: 198. House Robber

ゞ 浴缸里的玫瑰 2022-06-15 09:14 214阅读 0赞

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.分析

  1. def rob(self, nums):
  2. if not nums:
  3. return 0
  4. if(len(nums)<2):
  5. return nums[0]
  6. dp=[0 for i in nums]
  7. dp[0]=nums[0]
  8. dp[1]=max(nums[0],nums[1])
  9. for i in range(2,len(nums)):
  10. dp[i]=max(dp[i-2]+nums[i],dp[i-1])
  11. return dp[-1]

发表评论

表情:
评论列表 (有 0 条评论,214人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode 198.House Robber (打家劫舍)

    题目描述: 你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷