LeetCode刷题日记(Day19)

Problem 198. 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.

    Example:

    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.
    
  • 解题思路
    本题的意思是,在不能盗窃相邻两个房子的条件下,求盗贼所能盗取的最大金额。问题可以转化成求数组中不相邻的元素的和的最大值,可用动态规划的方法求解。令输入的数组为 nums,dp[i] 表示盗窃至第 i 家房子后获取的金额的最大值。
    令 len 表示为 nums 的长度,则:

  1. 当 len 为 0 时,表示没有房子,所以返回 0;
  2. 当 len 为 1 时,表示只有一个房子,所以 dp[0]=nums[0];
  3. 当 len 为 2 时,表示有两个房子,此时 dp[1]=max(nums[0], nums[1]);
  4. 当 len 为 3 时,表示有三个房子,因为不能盗取连续两个房子,所以 dp[2]=max(nums[0]+nums[2], nums[1]);
  5. 以此类推,对任意的 i > 2,dp[i] = max(nums[i]+dp[i-2], dp[i-1])
  • 代码实现
    以下分别是C++和python代码:
class Solution {
public:
    int rob(vector& nums) {
        int len = nums.size();
        if(len == 0)
            return 0;
        if(len == 1)
            return nums[0];
        vector dp(len, 0);
        dp[0] = nums[0];
        dp[1] = max(nums[0], nums[1]);
        for(int i = 2; i < len; ++i)
            dp[i] = max(nums[i]+dp[i-2], dp[i-1]);
        return dp[len-1];
    }
};
class Solution:
    def rob(self, nums:List[int]) -> int:
        length = len(nums)
        if length == 0:
            return 0
        if length == 1:
            return nums[0]
        dp = [0 for x in range(length)]
        dp[0] = nums[0]
        dp[1] = max(nums[0], nums[1])
        for i in range(2, length):
            dp[i] = max(dp[i-2]+nums[i], dp[i-1])
        return dp[length-1]

你可能感兴趣的:(LeetCode)