### 题目

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

Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

### 动态规划。递归版。复杂度 $O(n^2)$

T(n) = Math.max(nums[n] + T(n+2), nums[n+1] + T(n+3))

base case是：

• n >= nums.length: return 0;
• n == nums.length-1: return nums[nums.length-1]

#### 代码

public class Solution {
public int rob(int[] nums) {
int[] memo = new int[nums.length];
return dp(nums,0,memo);
}
public int dp(int[] nums, int cur, int[] memo) {
// base case
if (cur >= nums.length) { return 0; }
if (cur == nums.length - 1) { return nums[nums.length-1]; }
// dp
if (memo[cur] > 0) { return memo[cur]; }
memo[cur] = Math.max(nums[cur] + dp(nums,cur+2,memo), nums[cur+1] + dp(nums,cur+3,memo));
return memo[cur];
}
}


### 动态规划。迭代版。复杂度 $O(n)$

#### 代码

public class Solution {
public int rob(int[] nums) {
if (nums.length == 0) { return 0; }
int[] memo = new int[nums.length+3];
memo[nums.length-1] = nums[nums.length-1];
for (int i = nums.length-2; i >= 0; i--) {
memo[i] = Math.max(nums[i] + memo[i+2], nums[i+1] + memo[i+3]);
}
return memo[0];
}
}


### 时间复杂度 $O(n)$，空间复杂度 $O(1)$ 的变种

#### 代码

public class Solution {
public int rob(int[] nums) {
if (nums.length == 0) { return 0; }
int robPrevious = 0, notRobPrevious = 0;
int cur = nums.length-1;
do {
int notRobCurrent = Math.max(robPrevious,notRobPrevious);
int robCurrent = nums[cur--] + notRobPrevious;
notRobPrevious = notRobCurrent;
robPrevious = robCurrent;
} while (cur >= 0);
return Math.max(robPrevious,notRobPrevious);
}
}