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

你可能感兴趣的:(LeetCode,LeetCode解题报告)