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

Example 2:

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

Constraints:

  • 1 <= nums.length <= 100
  • 0 <= nums[i] <= 400

打家劫舍。

你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。

给定一个代表每个房屋存放金额的非负整数数组,计算你 不触动警报装置的情况下 ,一夜之内能够偷窃到的最高金额。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/house-robber
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是动态规划。这是一道动态规划的入门题目。

题目给定了数组 nums,既然是要计算偷所有房子的最大受益,我们暂且设有 n 个房子,所以这个问题转换为偷 n 个房子的最大受益是多少。同时既然是动态规划的题,那么我们需要分四步走

  • 定义子问题
  • 写出子问题的递推关系
  • 确定 DP 数组的计算顺序
  • 空间优化(可选)

这里为了计算偷 n 个房子的收益,我们可以试图先求子问题偷前 k 个房子的收益,因为前 k 个房子是 n 个房子的子问题且规模较小。

接下来我们来看子问题的递推关系。因为题目规定了不能偷相邻的两个房子,所以只有两种偷法,对于下标为 H0, H1, H2, ... Hk这些房子而言,我们可以

  • 偷前 k - 1 座房子,最后一座房子不偷
  • 偷最后一座房子和第 k - 2 座,跳过 k - 1 座不偷

此时我们需要判断的是这两种方案哪一种收益更大。dp[i] 的定义是如果偷前 i 个房子得到的最大收益是多少。

时间O(n)

空间O(n)

Java实现 - DP自下而上

 1 class Solution {
 2     public int rob(int[] nums) {
 3         // corner case
 4         if (nums == null || nums.length == 0) {
 5             return 0;
 6         }
 7 
 8         // normal case
 9         int len = nums.length;
10         int[] dp = new int[len + 1];
11         dp[0] = 0;
12         dp[1] = nums[0];
13         for (int i = 2; i <= len; i++) {
14             dp[i] = Math.max(dp[i - 2] + nums[i - 1], dp[i - 1]);
15         }
16         return dp[len];
17     }
18 }

 

Java实现 - DP自上而下,需要用到备忘录

 1 class Solution {
 2     int[] memo;
 3 
 4     public int rob(int[] nums) {
 5         int n = nums.length;
 6         memo = new int[n];
 7         Arrays.fill(memo, -1);
 8         return helper(nums, 0);
 9     }
10 
11     private int helper(int[] nums, int i) {
12         if (i >= nums.length) {
13             return 0;
14         }
15         if (memo[i] != -1) {
16             return memo[i];
17         }
18         // 偷当前房子或者偷下一个房子
19         int res = Math.max(nums[i] + helper(nums, i + 2), helper(nums, i + 1));
20         memo[i] = res;
21         return res;
22     }
23 }
24 
25 // dp自上而下

 

相关题目

198. House Robber

740. Delete and Earn

LeetCode 题目总结

posted @ 2020-05-29 06:33  CNoodle  阅读(210)  评论(0编辑  收藏  举报