• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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 }

 

posted @ 2015-04-12 03:36  neverlandly  阅读(589)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3