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. Linux内核分析——第六周学习笔记20135308

    第六周 进程的描述和进程的创建 一.进程描述符task_struct数据结构 1.操作系统三大功能 进程管理 内存管理 文件系统 2.进程控制块PCB——task_struct 也叫进程描述符,为了管 ...

  2. (第二周)读《我是一只IT小小鸟》有感

    读了蒋宇东学长的这篇描述他成长经历和生活感悟的博文,我真的收获了很多,有一种“相见恨晚”的感觉.同为航院的学子,我们有太多太多相同的生活学习经历. 我已经是一名大三的学生了,不知不觉中我大学生活的大部 ...

  3. 团队伊始——DreamCatcher

    我们的团队,队名是DreamCatcher,中文意思是追梦人,它是一首歌曲,所属专辑是<新世纪的曙光>. 这是一首很好听的歌曲,里面有一句歌词是: I'm a dream catcher ...

  4. Winform设置开机启动-操作注册表

    #region 设置开机运行 /// <summary> /// 设置开机运行 /// </summary> /// <param name="R_startP ...

  5. Ubuntu16解锁root

    administrator@rgqancy:~$ sudo passwd -u root [sudo] administrator 的密码: 对不起,请重试. [sudo] administrator ...

  6. [51CTO]新说MySQL事务隔离级别!

    新说MySQL事务隔离级别! 事务隔离级别这个问题,无论是校招还是社招,面试官都爱问!然而目前网上很多文章,说句实在话啊,我看了后我都怀疑作者弄懂没!本文所讲大部分内容,皆有官网作为佐证,因此对本文内 ...

  7. [转帖] 学习 Linux 大页的内存知识

    一.在解释什么情况下需要开启大页和为啥需要开启大页前先了解下Linux下页的相关的知识:以下的内容是基于32位的系统,4K的内存页大小做出的计算1)目录表,用来存放页表的位置,共包含1024个目录en ...

  8. 删除或添加最大化、最小化按钮 - 回复 "Tommy the CAT" 的问题

    本例效果图: 代码文件: unit Unit1; interface uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, ...

  9. Spring MVC的路径匹配规则 Ant-style

    Spring默认的策略实现了 org.springframework.util.AntPathMatcher,即Apache Ant的样式路径,Apache Ant样式的路径有三种通配符匹配方法(在下 ...

  10. Hbase之JavaAPI连接池

    源码: package HbaseOperation; import com.alibaba.fastjson.JSON; import org.apache.hadoop.conf.Configur ...