leetcode 337. House Robber III DP动态规划 + DFS深度有限遍历
来源:互联网 发布:python 图形化界面 编辑:程序博客网 时间:2024/06/10 00:08
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.
这道题意很简单,就是父亲节点和自己不可以同时抢劫,这里设置一个返回数字res,其中res[0]表示抢劫当前节点, res[1]不抢劫当前节点,直接DFS递归遍历即可实现。
建议和这道题leetcode 198. House Robber 入室抢劫 + DP求解 和 这道题 leetcode 213. House Robber II 入室抢劫 抢劫问题 一起学习。
代码如下:
/*class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}*//* * 这其实也是DP的解决方法之一, * */class Solution{ public int rob(TreeNode root) { if(root==null) return 0; int []res=getRes(root); return Math.max(res[0], res[1]); } /* * res[0]表示抢劫当前节点的记录的最大值 * res[1]表示不抢劫当前的结点的记录的最大值 * */ public int[] getRes(TreeNode root) { int[] res=new int[2]; if(root==null) return res; else { int[] left=getRes(root.left); int[] right=getRes(root.right); //抢劫当前节点,然后不抢劫其子节点 res[0]=root.val + left[1] + right[1]; //不抢劫当前节点,然后可以抢劫或者不抢劫其子节点 res[1]=Math.max(left[0], left[1]) + Math.max(right[0], right[1]); return res; } }}
- leetcode 337. House Robber III DP动态规划 + DFS深度有限遍历
- 动态规划解337. House Robber III
- leetcode 337. House Robber III-动态规划|Java|Python简洁高效
- Leetcode House Robber 动态规划
- [LeetCode][动态规划]House Robber
- [leetcode] 337. House Robber III
- LeetCode#337. House Robber III
- LeetCode *** 337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337. House Robber III
- [leetcode]337. House Robber III
- LeetCode-337.House Robber III
- LeetCode 337. House Robber III
- Leetcode 337. House Robber III
- leetcode 337. House Robber III
- LeetCode - 337. House Robber III
- 【LeetCode】337. House Robber III
- 【leetcode】337. House Robber III
- 51nod 1287 加农炮(分块)
- 浓墨重彩之OpenStack-12-ceilometer监控服务
- 关于Unicode编码和UTF-8编码
- 转载:卷积算子计算方法(卷积运算)
- FFmpeg解码视频帧为jpg图片保存到本地
- leetcode 337. House Robber III DP动态规划 + DFS深度有限遍历
- java集合
- HDU 5514 Frogs (容斥+数论)
- Java第一个简单的程序
- Codeforces Round #396 (Div. 2) E. Mahmoud and a xor trip dfs 按位考虑
- Django UnicodeEncodeError
- 【Hibernate】mysql版本影响hibernate操作数据库
- Kafka的基本shell命令
- Attribute 和 Parameter 的区别