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. 网络助手的NABCD分析

    我们小组这次做的软件名字叫为校园网络助手.本校校园网分为内网与外网认证两种,并且有着流量限制,所以我们设计出来了这项软件,它主要有着两项功能:一键WIFI与校内网盘. N--need.在学校里每当流量 ...

  2. 团队作业四-WBS练习

    我们团队开发的是四则运算,主要面对的用户是小学生.老师及学生家长.经过我们组成员的讨论和结合实际及自身能力,对团队成员分配任务,队长负责全局工作主要负责任务,统一进度,和适量的编码,露哥和阮磊主要负责 ...

  3. Win2008r2 设置 多用户同时远程

    Study From http://blog.sina.com.cn/s/blog_7ebe66420101tfln.html 1. 启动远程桌面,关闭防火墙 略过不提 2. 添加远程服务角色, 打开 ...

  4. 【转帖】 redis 命令 From https://www.cnblogs.com/zhouweidong/p/7550717.html

    redis命令详解   redis中添加key value元素:set key value;       获取元素:get key ;   redis中添加集合:lpush key value1 va ...

  5. 基于SOA的高并发和高可用分布式系统架构和组件详解

    基于SOA的分布式高可用架构和微服务架构,是时下如日中天的互联网企业级系统开发架构选择方案.在核心思想上,两者都主张对系统的横向细分和扩展,按不同的业务功能模块来对系统进行分割并且使用一定的手段实现服 ...

  6. Delphi中如何实现模拟组合按键,如发送Ctrl+F的按键

    利用 keybd_event函数可实现,如下面的代码用以实现在一个公共菜单中模拟Ctrl_F按钮以调用DBGridEH的查找对话框功能:这是在一个ActionList中的某一Action的OnExec ...

  7. 常用的Hql语句

    // HQL: Hibernate Query Language.// 特点:// >> 1,与SQL相似,SQL中的语法基本上都可以直接使用.// >> 2,SQL查询的是表 ...

  8. poj3468 A Simple Problem with Integers(线段树/树状数组)

    Description You have N integers, A1, A2, ... , AN. You need to deal with two kinds of operations. On ...

  9. 第一天进入博客这个神奇的领域 在此%%%erosun

    第一条博客水一水    等会要找一下调博客模板 独立动手,丰衣足食

  10. Spring Boot -Shiro配置多Realm

    核心类简介 xxxToken:用户凭证 xxxFilter:生产token,设置登录成功,登录失败处理方法,判断是否登录连接等 xxxRealm:依据配置的支持Token来认证用户信息,授权用户权限 ...