当前位置:网站首页>6. < tag dynamic planning and housebreaking collection (tree DP) > lt.198 Home raiding + lt.213 Looting II + lt.337 Looting III DBC
6. < tag dynamic planning and housebreaking collection (tree DP) > lt.198 Home raiding + lt.213 Looting II + lt.337 Looting III DBC
2022-07-22 02:33:00 【Caicai's big data development path】
lt.198. raid homes and plunder houses
[ Case needs ]
[ Thought analysis ]
Robbing is dp Classic problem solving , The five parts of dynamic planning are analyzed as follows :
- determine dp The meaning of array and its subscript .
dp[i] : Consider Subscripts i( Include i) The houses within , The maximum amount that can be stolen is dp[i]
- Determine the recurrence formula
decision dp[i] The key factor is
The first i Steal the room or not
,If you steal the first i room , that dp[i] = dp[i - 2] + nums[i], because dp Always get the current state from the previous state , If you want to steal i, So the last time I could only steal i - 2 Subscript house , use dp[i - 2] + nums[i] To get stolen dp[i] Amount obtained
If you don't steal the first i room , that dp[i] = dp[i - 1], That includes i - 1 The greatest value a room can steal
therefore , Recursive formula is to steal and not steal dp[i] Maximum value of : dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
- dp How to initialize an array
From the recurrence formula, we can get , dp Originally from dp[0] and dp[1] Start initialization , because dp[2] = Math.max(dp[1], dp[0] + nums[2]);
So we need to initialize dp[0] and dp[1], From the meaning of the title , dp[0] It means stealing the subscript 0 House of ,dp[0] = nums[0]
and , dp[1] You can choose to steal dp[0], Don't steal dp[1], Or not to steal dp[0], steal dp[1], therefore ,dp[1] = Math.max(nums[0], nums[1]);
- Determine the traversal order
dp[i] It's based on dp[i - 2] and dp[i - 1] Derived from , So it must be traversal from front to back !
- Give an example to deduce dp Array
[ Code implementation ]
class Solution {
public int rob(int[] nums) {
//1. determine dp[i], Indicates that the subscript is i The maximum amount you can steal from your house dp[i]
int len = nums.length;
int[] dp = new int[len];
//2. The recursive formula
// steal dp[i] = dp[i - 2] + nums[i]
// Don't steal dp[i - 1] = dp[i - 1]
// dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i])
//3. initialization
// dp[0] = nums[0];
// dp[1] = Math.max(nums[0], nums[1]);
dp[0] = nums[0];
if(len > 1)dp[1] = Math.max(nums[0], nums[1]);
//4. Traverse
for(int i = 2; i < len; i++){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
}
return dp[len - 1];
}
}
lt.213. raid homes and plunder houses II
[ Case needs ]
[ Thought analysis ]
- In fact, it is to split the ring into two queues , One is from 0 To n-1, The other is from 1 To n, Then return the two largest results .
[ Code implementation ]
class Solution {
public int rob(int[] nums) {
int len = nums.length;
if(len == 1)return nums[0];
if(len == 2)return Math.max(nums[0], nums[1]);
return Math.max(
myRob(Arrays.copyOfRange(nums, 0, len - 1)),
myRob(Arrays.copyOfRange(nums, 1, len)));
}
public int myRob(int[] nums) {
int n = nums.length;
int[] dp = new int[n + 1];
dp[0] = 0;
if(n > 1)dp[1] = nums[0];
for (int i = 2; i <= n; i++) {
dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i - 1]);
}
return dp[n];
}
}
lt.337. raid homes and plunder houses III
[ Case needs ]
[ Train of thought analysis 1 , Recurrence of violence ]
- Directly from root Nodes begin to recurse down ,
- Each layer can choose root node , And then add root Nodes on the left subtree of the left child , And plus root Nodes on the right subtree of the right child ;
- Or choose not root node , Directly from root The left child + root The right child node of starts to calculate .
[ Code implementation one ]
class Solution {
public int rob(TreeNode root) {
if(root == null)return 0;
if(root.left == null && root.right == null)return root.val;
// Steal the parent node , val1
// Then you need to skip root Direct left and right child nodes
int val1 = root.val;
// hold val1 + Subsequent recursive functions , This function is responsible for calculating root Left and right subtrees and root The left and right nodes on the subtree of the right child of
if(root.left != null)val1 += rob(root.left.left) + rob(root.left.right);
if(root.right != null)val1 += rob(root.right.left) + rob(root.right.right);
// Don't steal the parent node , val2
int val2 = rob(root.left) + rob(root.right);
return Math.max(val1, val2);
}
}
Train of thought analysis II , Mnemonic recurrence
- So you can use a map Save the calculated results , In this way, if you have calculated your grandchildren , Then the results of grandchildren can be reused when calculating children .
Train of thought Analysis III , Dynamic programming
边栏推荐
- Basic principle and configuration of switch
- SQL server数据库增量更新是根据 where 子句来识别的吗? 那做不到流更新吧? 每个表要
- Distributed transaction two-phase commit, at mode, TCC mode
- 小米12S Ultra产品力这么强老外却买不到 雷军:先专心做好中国市场
- DHCP协议
- 面试北京XX科技总结
- Sentinel fault tolerant rule persistence
- On Newton iteration
- 古中国文明
- VMware Workstation Pro virtual machine network three types of network cards and their usage
猜你喜欢
CTF解题思路
Skywalking server building and microservice access to skywalking
Creation of gateway routing service
Network layer protocol introduction
Example of implementing web server with stm32+enc28j60+uip protocol stack
VLAN and layer 3 switch
Gateway integrates sentinel to implement flow restriction rules for routing
CTF problem solving ideas
解决报错 OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized
thymeleaf应用笔记
随机推荐
H3C交换机查看相关的命令
(leisure) leetcode13 Roman to Integer
3511. Water pouring problem
js對象:檢測屬性是否存在
IP子网划分
[development tutorial 6] AI voice face recognition (Conference recorder / face punch card machine) - serial port
Flutter引入图形验证码,并保留SessionId
JS object: check whether the attribute exists
Ancient Chinese civilization
STM32+ENC28J60+UIP协议栈实现WEB服务器示例
Anti sandbox method
hi和hello两个请求引发的@RequestBody思考
【sklearn】数据集拆分 sklearn.moduel_selection.train_test_split
基于ABP实现DDD--领域服务、应用服务和DTO实践
已解决(selenium操作火狐浏览器报错)TypeError: __init__() got an unexpected keyword argument ‘firefox_options‘
mysql. h: No such file or directory
Js实现继承的6种方式
Basic principle and configuration of switch
电脑是怎样上网的 (二) 从网线到网络设备
DHCP protocol