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

Analyze

思考🤔:

[0, n - 1]
/ | ... \ \
[2, n - 1] [3, n - 1] [4, n - 1] ... [n - 1]
/
[4, n - 1]: 此时找到了重复子项
  • 状态的定义(即函数的定义): 考虑偷取 [m, n - 1] 范围内的房子
  • 状态转移: f(0) = Math.max(v(0) + f(2), v(1) + f(3), v(2) + f(4), ..., v(n - 3) + f(n - 1), v(n - 2), v(n - 1))

记忆化递归:

/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
return find(nums, {}, 0)
}
var find = function(nums, cache, start) {
if (typeof nums[start] !== 'number') return 0
const length = nums.length
let sum = 0
for (let i = start; i < length; i++) {
if (typeof cache[i] !== 'number') {
cache[i] = find(nums, cache, i + 2)
}
sum = Math.max(sum, nums[i] + cache[i])
}
return sum
}

动态规划:

/**
* @param {number[]} nums
* @return {number}
*/
var rob = function(nums) {
const length = nums.length
const cache = {}
let max = 0
for (let i = length - 1; i >= 0; i--) {
for (let m = i; m <= length - 1; m++) {
if (typeof cache[m] !== 'number') {
cache[m] = Math.max(nums[m] + (cache[m + 2] || 0), cache[m + 1] || 0)
}
max = Math.max(max, cache[m])
}
}
return max
}