Loading

【leetcode】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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.

Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.

  你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。

Example 1:

Input: nums = [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.

Leetcode上类似的题目还有几道,都是比较经典的打家劫舍问题,对于这种求截取金额最大的问题,一般都用动态规划。
动态规划三要素:1、选择dp数组 2、初始化 3、状态如何转移
设一个数组dp[n],表示偷到第n户人家最大的收益额。状态转移方程是:
dp[n]=max(dp[n-2]+nums[n],dp[n-1])

这里有个小trick是需要在dp[n]前面填一个0,防止dp[n-2]数组越界。
CPP代码:
class Solution {
public:
    int rob(vector<int>& nums) {
        // 经典动态规划题目  打家劫舍
        // 如何构建状态转移方程
        // dp[n] 当前数组最大的盗取收益
        int n=nums.size();
        if(n==0) return 0;
        vector<int>dp(n+1,0);
        dp[1]=nums[0];
        for(int i=2;i<=n;++i){
            dp[i]=max(dp[i-2]+nums[i-1],dp[i-1]); //偷当前的家的财产 以及不偷
        }
        return dp[n];
    }
};

    C 代码:

int rob(int* nums, int numsSize){
  if(numsSize==0) return 0;
  int dp[101]={0};
  dp[1]=nums[0];
  for(int i=2;i<=numsSize;++i){
       dp[i]=(dp[i-2]+nums[i-1])>dp[i-1]?(dp[i-2]+nums[i-1]):dp[i-1]; //偷当前的家的财产 以及不偷
    }
  return dp[numsSize];
}

 Python 代码:

 

class Solution:
    def rob(self, nums: List[int]) -> int:
        # 动态规划要素 选择dp数组 初始化 状态如何转移 dp偷到当前房子最高的前
        if not nums:
            return 0
            
        n=len(nums)
        dp=[0 for _ in range(n+1)]
        dp[1]=nums[0]

        for i in range(2,n+1):
            dp[i]=max(dp[i-1],nums[i-1]+dp[i-2]) #状态转移
        return dp[-1]

 

 

 


posted @ 2021-12-01 09:29  aalanwyr  阅读(34)  评论(0编辑  收藏  举报