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

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.

解题思路

很明显是个动态规划问题,这里的转移方程也很明显,res[i] = max(res[i - 1] , res[i - 2] + num[i-2])。res表示当前我们到这一家所能够获得的最大的利润。这个利润简单地说就取决于强不强这家,并且注意限制是不能抢连续的两家。

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]

你可能感兴趣的:(LeetCode)