【LeetCode】198、打家劫舍

198、House Robber打家劫舍

难度:简单

题目描述

  • 英文:

    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:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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.


    输入: [1,2,3,1]
    输出: 4
    解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
    偷窃到的最高金额 = 1 + 3 = 4 。

    Example 2:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    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.


    输入: [2,7,9,3,1]
    输出: 12
    解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
    偷窃到的最高金额 = 2 + 9 + 1 = 12 。

解题思路

思路一

动态规划,根据题意,不能窃取相邻的房屋,那么第$n$天的最高金额,要么等于第$n-1$天的最高金额,要么等于$n-2$天的最高金额加上第$n$天可获得的金额。

用$f (n)$表示第$n$天的最高金额,$p_n$表示第$n$天可获得的金额,则$f (n) = \max (f(n-1) , f(n-2)+p_n)$,其中,$f(1) = p_1 , f(2)=\max (p_1, p_2)​$。

Ps. 开始简单的以为,就是奇数位求和,偶数位求和,然后取最大值,后来发现不对,只要求有间隔,但间隔不一定为1,如测试用例[2,1,1,2],则间隔为2,取首尾两个元素时为最大值。

代码提交

Python3,用时64ms,内存13.1M

时间复杂度:$O (n) ​$

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums) == 1:
return nums[0]

temp = [nums[0], max(nums[0], nums[1])]
for i in range(2, len(nums)):
temp.append(max(temp[i-1], temp[i-2]+nums[i]))
return temp[-1]

在Python中,list添加元素的方法,expend效率要高于append,调整后,用时52ms,如下:

1
2
3
4
5
6
7
8
9
10
11
class Solution:
def rob(self, nums: List[int]) -> int:
if not nums:
return 0
if len(nums) == 1:
return nums[0]

temp = [nums[0], max(nums[0], nums[1])]
for i in range(2, len(nums)):
temp.extend([max(temp[i-1], temp[i-2]+nums[i])])
return temp[-1]
-------------本文结束感谢您的阅读-------------
0%