【leetcode】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.code

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.it

解題思路

很明顯是個動態規劃問題,這裏的轉移方程也很明顯,res[i] = max(res[i - 1] , res[i - 2] + num[i-2])。res表示當前咱們到這一家所可以得到的最大的利潤。這個利潤簡單地說就取決於強不強這家,而且注意限制是不能搶連續的兩家。io

class Solution:
    # @param num, a list of integer
    # @return an integer
    def rob(self, num):
        res = [0] * (len(num) + 2)
        for i in range(2,len(num)+2):
            res[i] = max(res[i - 1] , res[i - 2] + num[i-2])
        return res[-1]
相關文章
相關標籤/搜索