Recursion (Brute Force)
Intuition
The circular constraint means the first and last houses cannot both be robbed. We can break this into two linear subproblems: one that considers houses 0 through n-2 (excluding the last) and another that considers houses 1 through n-1 (excluding the first). For each subproblem, we use the same recursive approach as House Robber I: at each house, choose to rob or skip.
Algorithm
- If there is only one house, return its value.
- Solve the linear House Robber problem for `nums[0..n-2]`.
- Solve the linear House Robber problem for `nums[1..n-1]`.
- Return the maximum of the two results.
O(2^n) for each subproblem without memoizationSpaceO(n) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
int robLinear(vector<int>& nums, int start, int end) {
if (start > end) return 0;
return max(nums[start] + robLinear(nums, start + 2, end),
robLinear(nums, start + 1, end));
}
int rob(vector<int>& nums) {
int n = nums.size();
if (n == 1) return nums[0];
return max(robLinear(nums, 0, n - 2), robLinear(nums, 1, n - 1));
}
};class Solution {
private int robLinear(int[] nums, int start, int end) {
if (start > end) return 0;
return Math.max(nums[start] + robLinear(nums, start + 2, end),
robLinear(nums, start + 1, end));
}
public int rob(int[] nums) {
int n = nums.length;
if (n == 1) return nums[0];
return Math.max(robLinear(nums, 0, n - 2), robLinear(nums, 1, n - 1));
}
}from typing import List
class Solution:
def rob(self, nums: List[int]) -> int:
def rob_linear(start: int, end: int) -> int:
if start > end:
return 0
return max(nums[start] + rob_linear(start + 2, end),
rob_linear(start + 1, end))
n = len(nums)
if n == 1:
return nums[0]
return max(rob_linear(0, n - 2), rob_linear(1, n - 1))func rob(nums []int) int {
n := len(nums)
if n == 1 {
return nums[0]
}
var robLinear func(start, end int) int
robLinear = func(start, end int) int {
if start > end {
return 0
}
take := nums[start] + robLinear(start+2, end)
skip := robLinear(start+1, end)
if take > skip {
return take
}
return skip
}
a := robLinear(0, n-2)
b := robLinear(1, n-1)
if a > b {
return a
}
return b
}