当前位置: 代码迷 >> 综合 >> Leetcode 198. House Robber Easy(python)
  详细解决方案

Leetcode 198. House Robber Easy(python)

热度:2   发布时间:2023-11-26 07:56:01.0

Leetcode 198. House Robber Easy

  • 题目
  • 解法:动态规划

题目

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.

Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.

Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.

解法:动态规划

动态规划的递推公式为:

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

解读起来就是,分成两种情况,抢劫当前房屋和不抢劫当前房屋,如果抢劫当前房屋,那么现在的值就是当前房屋的值nums[i]和不抢劫前一幢房屋的最大值dp[i-2]. 如果不抢劫当前房屋,那么就是抢劫前一幢房屋时的最大值

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

时间复杂度:O(N)
空间复杂度:O(N)

  相关解决方案