LeetCode:House Robber

来源:互联网 发布:dota2永恒矩阵 编辑:程序博客网 时间:2024/06/12 00:51

题目: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.

解题思路:本题可以看做求nums数组中不相邻的数字的最大值和。

这是一个动态规划(DP)问题,设一个数组nums:

如果len(nums)=1,那么sum(0)=nums[0]
如果len(nums)=1,那么sum(1)=max(nums[0],nums[1])
如果len(nums)=2,那么sum(2)=max(sum(0)+nums[i],sum(1))
以此类推,sum(k)=max(sum(k-2)+nums[k],sum(k-1))

代码:

class Solution(object):    def rob(self,nums):        k=len(nums)        sum=[0]*k #或者sum=[0 for i in range(k)]        if k== 0:            return 0        for i in range(k):            if i == 0:                sum[i]=nums[0]            if i ==1:                sum[i]=max(nums[0],nums[1])            sum[i]=max(sum[i-2]+nums[i],sum[i-1])        return sum[-1]
0 0
原创粉丝点击