Leetcode: 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 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.

This particular problem and most of others can be approached using the following sequence: https://leetcode.com/problems/house-robber/discuss/156523/From-good-to-great.-How-to-approach-most-of-DP-problems. 

  1. Find recursive relation
  2. Recursive (top-down)
  3. Recursive + memo (top-down)
  4. Iterative + memo (bottom-up)
  5. Iterative + N variables (bottom-up)

1. Find recursive relation

  rob(i) = max(rob(i-2) + cur, rob(i-1))

2. Recursive (top-down)

1 public int rob(int[] nums) {
2     return rob(nums, nums.length - 1);
3 }
4 private int rob(int[] nums, int i) {
5     if (i < 0) {
6         return 0;
7     }
8     return Math.max(rob(nums, i - 2) + nums[i], rob(nums, i - 1));
9 }

3.  Recursive + memo (top-down).

 1 int[] memo;
 2 public int rob(int[] nums) {
 3     memo = new int[nums.length + 1];
 4     Arrays.fill(memo, -1);
 5     return rob(nums, nums.length - 1);
 6 }
 7 
 8 private int rob(int[] nums, int i) {
 9     if (i < 0) {
10         return 0;
11     }
12     if (memo[i] >= 0) {
13         return memo[i];
14     }
15     int result = Math.max(rob(nums, i - 2) + nums[i], rob(nums, i - 1));
16     memo[i] = result;
17     return result;
18 }

4.  Iterative + memo (bottom-up)

 1 public int rob(int[] nums) {
 2     if (nums.length == 0) return 0;
 3     int[] memo = new int[nums.length + 1];
 4     memo[0] = 0;
 5     memo[1] = nums[0];
 6     for (int i = 1; i < nums.length; i++) {
 7         int val = nums[i];
 8         memo[i+1] = Math.max(memo[i], memo[i-1] + val);
 9     }
10     return memo[nums.length];
11 }

5. Iterative + 2 variables (bottom-up)

 1 /* the order is: prev2, prev1, num  */
 2 public int rob(int[] nums) {
 3     if (nums.length == 0) return 0;
 4     int prev1 = 0;
 5     int prev2 = 0;
 6     for (int num : nums) {
 7         int tmp = prev1;
 8         prev1 = Math.max(prev2 + num, prev1);
 9         prev2 = tmp;
10     }
11     return prev1;
12 }
原文地址:https://www.cnblogs.com/EdwardLiu/p/4418967.html