LeetCode 198. House Robber

来源:互联网 发布:linux top n 1 编辑:程序博客网 时间:2024/06/03 19:30

题目描述

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

思路

简单动归。
f(n) = max(num[i] + f(n - 2), f(n - 1))

代码

class Solution:    def rob(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums) == 0:            return 0        if len(nums) == 1:            return nums[0]        if len(nums) == 2:            return max(nums[0], nums[1])        total_list = [nums[0], max(nums[0], nums[1])]        for i, v in enumerate(nums):            if i == 0 or i == 1:                continue            total_list.append(max(total_list[i - 1], total_list[i - 2] + nums[i]))        return total_list[len(nums) - 1]