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.

Example

Given [3, 8, 4], return 8.

分析:

因为“偷”第一个或者“偷”第二个对后面的选择是有影响的,所以从后往前推算更好。

total[i] = Math.max(A[i] + total[i + 2], total[i + 1]);

A[i] + total[i + 2] 指的是偷第i家。

total[i + 1] 指的是不偷i家。

 public class Solution {
/**
* @param A: An array of non-negative integers.
* return: The maximum amount of money you can rob tonight
*/
public long houseRobber(int[] A) {
if (A == null || A.length == ) return ;
if (A.length == ) return A[];
if (A.length == ) return Math.max(A[], A[]); long[] total = new long[A.length];
int length = total.length;
total[length - ] = A[length - ];
total[length - ] = Math.max(A[length - ], A[length - ]); for (int i = length - ; i >= ; i--) {
total[i] = Math.max(total[i + ] + A[i], total[i + ]);
}
return total[];
}
}

House Robber II

After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

Example

nums = [3,6,4], return 6.

分析:

现在是一个环了,感觉好像找不到起始点。其实反过来想,就是头尾不能同时选而已。所以我们分别选取两个不同的起始点和结束点,跑两次就可以了。

 public class Solution {

     public int houseRobber2(int[] nums) {
if (nums == null || nums.length == ) return ;
if (nums.length == ) return nums[];
return Math.max(getMax(nums, , nums.length - ), getMax(nums, , nums.length - ));
} public int getMax(int[] nums, int start, int end) {
if (start == end) return nums[start];
if (start + == end) return Math.max(nums[start], nums[end]); int[] total = new int[end - start + ];
int m = total.length;
total[m - ] = nums[end];
total[m - ] = Math.max(nums[end], nums[end - ]); for (int i = m - ; i >= ; i--) {
total[i] = Math.max(nums[end - (m - i) + ] + total[i + ], total[i + ]);
}
return total[];
}
}

House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example

  3
/ \
2 3
\ \
3 1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

    3
/ \
4 5
/ \ \
1 3 1

Maximum amount of money the thief can rob = 4 + 5 = 9.

分析:

看到树,想都不用多想,立马想到递归。关键是这个递归怎么写啊?

既然我们不知道是否把root包含进去是否是最优,那么我们就创建一个函数,返回一个数组,这个数组包含两种情况下的最大值。

 public class Solution {

     public int rob(TreeNode root) {
if(root == null) return ; int[] result = helper(root);
return Math.max(result[], result[]);
} public int[] helper(TreeNode root){
if(root == null){
return new int[]{, };
} int[] result = new int[];
int[] left = helper(root.left);
int[] right = helper(root.right); // result[0] is when root is selected, result[1] is when not.
result[] = root.val + left[] + right[];
result[] = Math.max(left[], left[]) + Math.max(right[], right[]); return result;
}
}

House Robber I & II & III的更多相关文章

  1. 解题思路:house robber i && ii && iii

    这系列题的背景:有个小偷要偷钱,每个屋内都有一定数额的钱,小偷要发家致富在北京买房的话势必要把所有屋子的钱都偷了,但是屋子之内装了警报器,在一定条件下会触发朝阳群众的电话,所以小偷必须聪明一点,才能保 ...

  2. Leetcode 137. Single Number I/II/III

    Given an array of integers, every element appears twice except for one. Find that single one. 本题利用XO ...

  3. 买卖股票的最佳时机I II III IV

    I 假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格.如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润. II 假设有一个数组,它的第i个元素是一个给定的股票 ...

  4. LeetCode Single Number I / II / III

    [1]LeetCode 136 Single Number 题意:奇数个数,其中除了一个数只出现一次外,其他数都是成对出现,比如1,2,2,3,3...,求出该单个数. 解法:容易想到异或的性质,两个 ...

  5. 1. Two Sum I & II & III

    1. Given an array of integers, return indices of the two numbers such that they add up to a specific ...

  6. 【LeetCode】Single Number I & II & III

    Single Number I : Given an array of integers, every element appears twice except for one. Find that ...

  7. [Leetcode][JAVA] Best Time to Buy and Sell Stock I, II, III

    Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a gi ...

  8. LeetCode:Best Time to Buy and Sell Stock I II III

    LeetCode:Best Time to Buy and Sell Stock Say you have an array for which the ith element is the pric ...

  9. [Locked] Shortest Word Distance I & II & III

    Shortest Word Distance Given a list of words and two words word1 and word2, return the shortest dist ...

随机推荐

  1. 关于 error C2039: “create”: 不是“cocos2d::GLView”的成员的解决方法

    问题: 跑一个demo,因为是涉及3.x版本的引擎,不是很熟悉,在VS2013上运行,报错 error C2039: “create”: 不是“cocos2d::GLView”的成员 解决: 通过查阅 ...

  2. Drools解决积分问题

    http://blog.csdn.net/quzishen/article/details/6163012 http://www.cnblogs.com/ityouknow/p/7297524.htm ...

  3. Oracle client 使用 .net程序连接 数据库时 出现 8.1.7 的解决办法

    1. GS产品 连接oracle数据库时出现错误图示 2. 其实解决这个问题的办法很简单 一般是 修改一下 Oracle的app 目录的权限 最简单的办法是增加 everyone 权限 然后重启机器即 ...

  4. 外媒速递:系统管理员必须掌握的20条Linux命令

    [51CTO.com原创稿件]外媒速递是核子可乐精选的近日国外媒体的精彩文章推荐,希望大家喜欢! 今天推荐的内容包括:系统管理员必须掌握的20条Linux命令.五款最佳Linux屏幕记录应用.MySQ ...

  5. 使用spring单元调试出错initializationError

    1.引入spring jar包之后,单元测试一直出错,提示initializationError. 2.在网上看说是junit版本的问题,引入其他版本之后,还是不对. 3.最后发现是需要引入 这两个j ...

  6. linux 命令大全,我去

    系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...

  7. Django时间时区问题(received a naive datetime while time zone support is active)

    在django1.4以后,存在两个概念 naive time 与 active time. 简单点讲,naive time就是不带时区的时间,Active time就是带时区的时间. 举例来说,使用d ...

  8. Jamie's Contact Groups POJ - 2289(多重匹配 最大值最小化 最大流)

    Jamie's Contact Groups Time Limit: 7000MS   Memory Limit: 65536K Total Submissions: 8567   Accepted: ...

  9. 【BZOJ1293】[SCOI2009]生日礼物(单调队列)

    [BZOJ1293][SCOI2009]生日礼物(单调队列) 题面 BZOJ 洛谷 题解 离散之后随便拿单调队列维护一下就好了. #include<iostream> #include&l ...

  10. 【ARC082E】ConvexScore

    Description 给定二维直角坐标系上的N个点\((X_i,Y_i)\),定义一个有N个点中的部分点所构成点集为"凸点集",当且仅当该集合内的所有点恰好构成一个面积为正的凸多 ...