LeetCode-198. House Robber

0.原题

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:

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.

Example 2:

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.

 

1.失败的解法:

所以,遍历吧!

从头开始抢劫,对每间房子,强盗都有两种可能:

  1. 抢:如果抢了第n间房子,那么第n+1间房子就不能再抢了,所以问题就变成了nums[n+2:end]的抢劫问题
  2. 不抢:那么问题就变成了nums[n+1:end]的抢劫问题

所以,每一间房子都作两种假设,通过递归+遍历,就可查找所有抢劫方案。

咋一看,思路没问题!

class Solution:
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        else:
            self.nums = nums
            self.end = len(nums)
            self.max_amount = 0
            self.fun(0,0)
            return self.max_amount

    def fun(self,amount,index):
        if self.end - index <= 2:
            amount += max(self.nums[index:self.end])
            self.max_amount = max(amount,self.max_amount)
        else:
            #Rob house[index]
            self.fun(amount + self.nums[index],index + 2)
            #Don't rob house[index]
            self.fun(amount,index +1)

if __name__ == '__main__':
    nums = [1,2,3,1]
    solution = Solution()
    print(solution.rob(nums))

结果:

时间超时了,为什么呢?

每间房子都有两种可能,所以这样的算法,时间复杂度是O(2^n),这种方法显然是不合适的

但如果我们根据index的值,画出状态变化的搜索树:

很容易发现,其实很多搜索状态是重复的,而这些重复的操作可以通过辅助数组记录,从而起到剪枝的效果。

 

2.更优的算法

如果我们把已经遍历过的状态记录下来,这样就能够极大地降低计算量。

根据这样的思想,优化后的代码如下:

class Solution:
    def rob(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        else:
            self.nums = nums
            self.end = len(nums)
            self.amounts = [0 for _ in range(len(nums))]
            self.visited = [False for _ in range(len(nums))]
            max_amount = self.fun(0)
            return max_amount

    def fun(self,index):
        if self.end - index <= 2:
            amount = max(self.nums[index:self.end])
            self.amounts[index] = amount
            return amount
        else:

            if not self.visited[index]:
                # Rob house[index]
                amount1 = self.nums[index] + self.fun(index + 2)
                # Don't rob house[index]
                amount2 = self.fun(index + 1)
                amount = max(amount1,amount2)
                self.amounts[index] = amount
                self.visited[index] = True
                return amount
            else:
                return self.amounts[index]


if __name__ == '__main__':
    nums = [1,2,3,1]
    solution = Solution()
    print(solution.rob(nums))

这个程序与第一个程序的区别在于,记录了相同遍历状态的返回值,并设置visited列表对各个状态进行记录,从而起到了剪枝的效果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值