198. House Robber [easy] (Python)

题目链接

https://leetcode.com/problems/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.

题目翻译

你要去一条街上偷钱,每一户人家都有一定量的钱,但是你不能偷相邻两家的,因为相邻的两家有安保系统相连,偷了你就被警察叔叔带走了(什么鬼安保系统= =)。
给定一个非负数组,代表每家有多少钱。求出在不被警察叔叔带走的情况下,你今晚最多能偷多少钱。

思路方法

思路一

这个问题可以这么想,假设只有一家,那么你只能偷这家;假设有两家,那么你要判断两家哪个钱多,偷哪个;依次类推,假设有n家,那么你要判断“偷第n家不偷第n-1家且前n-2家尽量多的偷”和“不偷第n家且前n-1家尽量多的偷”,哪个得到的钱多偷哪个。
你可以递归求解,然而复杂度太高无法AC。所以应该记录已经计算过的结果,于是这变成一个动态规划问题。

代码

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

思路二

当然你会发现,上面的代码使用的空间是冗余的,因为每次循环只会用到前两个数据。所以代码可以降低空间复杂度到O(1)。

代码

class Solution(object):
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        now = last = 0
        for i in nums:
            last, now = now, max(i+last, now)
        return now

PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.csdn.net/coder_orz/article/details/51555813

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值