【leetcode】198.HouseRobber
198.HouseRobber
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.
Tips:你是一名职业抢劫犯,计划在街上抢劫房屋。每个房子都有一定数量的钱,唯一能阻止你抢劫的限制就是相邻的房子有相连的安全系统,当相邻的两个房子在同一晚被抢劫,就会自动报警。给定一组非负整数,表示每个房子的钱数,确定你今晚可以抢劫的最大金额,而不用报警。
输入:int[] 表示每个房子内的钱数。
输出:能抢劫的最大钱数。
只要比较当前值,与前一个值加上nums[]之和的大小即可。
package easy; public class L198HouseRobber { public int rob(int[] nums) {
int pre = 0;
int cur=0;
int len = nums.length;
if (nums == null || len == 0)
return 0;
for(int i=0;i<len;i++){
int temp=Math.max(pre+nums[i], cur);
pre=cur;
cur=temp;
}
return cur;
} public static void main(String[] args) {
int[] nums = { 2, 1, 1, 2 ,1,1};
int[] nums1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
int[] nums2={2,7,9,3,1};
L198HouseRobber l98 = new L198HouseRobber();
int money = l98.rob(nums2);
System.out.println(money);
}
}
动态规划的方法,维护一个数组dp,dp[i]表示到i位置时不相邻数能形成的最大和。
public int rob(int[] nums) {
if(nums.length<=0) return 0;
if(nums.length==1) return nums[0];
int[] dp=new int[nums.length];
dp[0]=nums[0];
dp[1]=Math.max(nums[0],nums[1]);
for(int i=2;i<nums.length;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[nums.length-1];
}
213. House Robber II
Question: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.
Tips:小偷换了一个地方接着偷,这次所有的房子围成一个圈。怎么偷钱最多,而不惊动警察。
思路:由于上一个题目房子在一条直线上,现在的房子是在一个圆环内,我们可以想办法将圆环拆成直线。第一步首先决定是否偷第一个房子。可以将问题拆分为两种情况,(0~nums.length-1)与(1~nums.length-2).拆分之后就又变会第一个问题。
class Solution {
public int rob(int[] nums) {
int len=nums.length;
if(len<=0) return 0;
if(len==1) return nums[0];
return Math.max(rob(nums,0,len-2),rob(nums,1,len-1));
}
public int rob(int[] nums,int start,int end) {
int[] dp = new int[nums.length]; if(start==0){
dp[0]=nums[0];
dp[1]=Math.max(nums[0],nums[1]);
}
else{
dp[1]=nums[1];
}
for(int i=2;i<=end;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[end];
}
}
337. House Robber III
Question: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 1:
3
/ \
2 3
\ \
3 1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
Example 2:
3
/ \
4 5
/ \ \
1 3 1
Maximum amount of money the thief can rob = 4 + 5 = 9.
Tips:小偷又换一个地方接着偷。此地房子只有一个入口叫root,每个房子有且只有一个父房子。求可偷最大金额。
思路:这个题给我的第一感觉就是需要按层得出财富最大值,分为两种情况:
(1)包含root结点,以及之后的第三层结点
(2)不包含root结点,从第二层开始隔层相加。
代码:
public int rob(TreeNode root) {
if(root==null)return 0;
int ans=0;
if(root.left!=null){
ans+=rob(root.left.left)+rob(root.left.right);
}
if(root.right!=null){
ans+=rob(root.right.left)+rob(root.right.right);
}
return Math.max(ans+root.val,rob(root.left)+rob(root.right));
}
但是这种方法存在重复计算非常多。所以我们可以通过保存计算结果来减少计算量。(使用hashmap存储中间结果。)
public int rob(TreeNode root){
if(root==null)return 0;
HashMap<TreeNode,Integer> map= new HashMap<>();
return rob(root,map);
}
public int rob(TreeNode root,HashMap map) {
if(root==null)return 0;
int ans=0;
if(map.containsKey(root)){
return (int)map.get(root);
}
if(root.left!=null){
ans+=rob(root.left.left,map)+rob(root.left.right,map);
}
if(root.right!=null){
ans+=rob(root.right.left,map)+rob(root.right.right,map);
}
ans=Math.max(ans+root.val,rob(root.left,map)+rob(root.right,map));
map.put(root,ans);
return ans;
}
【leetcode】198.HouseRobber的更多相关文章
- 【LeetCode】198. House Robber 打家劫舍 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 递归 + 记忆化 动态规划 优化动态规划空间 ...
- 【LeetCode】198 - House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount ...
- 【LeetCode】198. 打家劫舍
打家劫舍 你是一个专业的小偷,计划偷窃沿街的房屋.每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警. 给定 ...
- 【LeetCode】386. Lexicographical Numbers 解题报告(Python)
[LeetCode]386. Lexicographical Numbers 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博 ...
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...
- 【Leetcode】Pascal's Triangle II
Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...
- 53. Maximum Subarray【leetcode】
53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...
- 27. Remove Element【leetcode】
27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...
- 【刷题】【LeetCode】007-整数反转-easy
[刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...
随机推荐
- A1048
给n个正整数,再给一个m,如果n个数中存在a+b=m(a<=b),则输出a,b. 如果有两组以上,则输出a最小的一组. #include<cstdio> #include<al ...
- 基于visual studio 2017 以及cubemx 搭建stm32的开发环境(1)
参考如下文档: 传送门:http://www.stm32cube.com/article/128 如果链接不存在的话,下载我截屏好的图: 传送门:https://pan.baidu.com/s/1NC ...
- 【 C 】高级字符串查找之 strspn 和 strcspn 的思考
我的CSDN博客 strspn 这个库函数是真的很难理解,看了很多中文描述,反正都是不知所云,给出一系列的例子,结果也是让我瞠目结舌,荒唐.荒谬.荒诞! 特此记录理解过程,最后竟然是百度百科让我明白了 ...
- 20155321 2016-2017-2《Java程序设计》课堂实践项目
20155321 2016-2017-2<Java程序设计>课堂实践项目 关于String类 split方法 charAt方法 项目题目: 模拟实现Linux下Sort -t : -k 2 ...
- Firefox+Burpsuite抓包配置(可抓取https)
0x00 以前一直用的是火狐的autoproxy代理插件配合burpsuite抓包 但是最近经常碰到开了代理却抓不到包的情况 就换了Chrome的SwitchyOmega插件抓包 但是火狐不能抓包的问 ...
- day 14 元组
1. 使用场景? # 列表list 数据类型相同, #rwx文件 100个人的名字, # 用字典 dict ['dɪkt] 很多信息描述1个人, # tuple [ˈtʌpəl] #只读文件 不能修改 ...
- rsync + inotify 数据实时同步
一.rsync介绍 rsync英文全称为Remote synchronization,从软件的名称就可以看出来,Rsync具有可是本地和远程两台主机之间的数据快速复制同步镜像.远程备份的功能,这个功能 ...
- python的种类
Cpython Python的官方版本,使用C语言实现,使用最为广泛,CPython实现会将源文件(py文件)转换成字节码文件(pyc文件),然后运行在Python虚拟机上. Jyhton ...
- Python单元测试--unittest(一)
unittest模块是Python中自带的一个单元测试模块,我们可以用来做代码级的单元测试. 在unittest模块中,我们主要用到的有四个子模块,他们分别是: 1)TestCase:用来写编写逐条的 ...
- Java飞机大战MVC版
PlaneWar Java飞机大战MVC版 //无聊时偷的雷霆战机素材写了一个飞机大战,本意是练习mvc,但写得还是不清晰 github下载:https://github.com/dejavudwh/ ...