Recursion (Brute Force)
Intuition
At each house we have two choices: rob it (and skip the next house) or skip it (and move to the next house). This creates a binary decision tree. The recurrence is rob(i) = max(nums[i] + rob(i+2), rob(i+1)). Without memoization, many subproblems are recomputed, resulting in exponential time.
Algorithm
- Define a recursive function starting at index `0`.
- Base case: if index `>= n`, return `0`.
- Option 1: rob the current house and recurse from `index + 2`.
- Option 2: skip the current house and recurse from `index + 1`.
- Return the maximum of both options.
O(2^n)SpaceO(n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int rob(vector<int>& nums) {
return helper(nums, 0);
}
int helper(vector<int>& nums, int i) {
if (i >= nums.size()) return 0;
return max(nums[i] + helper(nums, i + 2), helper(nums, i + 1));
}
};class Solution {
public int rob(int[] nums) {
return helper(nums, 0);
}
private int helper(int[] nums, int i) {
if (i >= nums.length) return 0;
return Math.max(nums[i] + helper(nums, i + 2), helper(nums, i + 1));
}
}from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
def helper(i: int) -> int:
if i >= len(nums):
return 0
return max(nums[i] + helper(i + 2), helper(i + 1))
return helper(0)func rob(nums []int) int {
var helper func(i int) int
helper = func(i int) int {
if i >= len(nums) {
return 0
}
take := nums[i] + helper(i+2)
skip := helper(i + 1)
if take > skip {
return take
}
return skip
}
return helper(0)
}