当前位置:网站首页>[leetcode] path sum II (first glimpse recursion + backtracking)
[leetcode] path sum II (first glimpse recursion + backtracking)
2022-06-11 01:50:00 【xiaoshijiu333】
#LeetCode A daily topic 【 Special topic of binary tree 】
- The sum of the paths II
https://leetcode-cn.com/problems/path-sum-ii/ - analysis
Look for a binary tree all From the root node to the leaf node The path sum is equal to the given target sum
Consider depth first search , Whenever a leaf node is reached , Judge whether the current value meets the goals and , To add it to the final result set ;
It should be noted that , When a certain root node and the following nodes are traversed , Keep going up , Need to pay attention to backtracking , Otherwise, it will affect the next recursive result set - Realization
List<List<Integer>> ans = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
LinkedList<Integer> res = new LinkedList<>();
pathSum(root, targetSum, res);
return ans;
}
// Depth-first search + to flash back
private void pathSum(TreeNode root, int targetSum, LinkedList<Integer> res) {
if (root == null) return;
res.add(root.val);
if (root.left == null && root.right == null) {
// The leaf node satisfies the final condition
if (root.val == targetSum) {
// want new A collection goes in , Otherwise, it will be synchronously modified later
ans.add(new LinkedList<>(res));
}
}
pathSum(root.left, targetSum - root.val, res);
pathSum(root.right, targetSum - root.val, res);
// Go back , Remove the current node from the collection
res.pollLast();
}
LeetCode Time consuming :1ms
- Option two
If you do not use backtracking , Make sure that between each recursion list Transmission does not affect each other , You can also generate a new set before each recursion , But there will be a lot of extra time and space overhead
List<List<Integer>> ans = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
LinkedList<Integer> res = new LinkedList<>();
pathSum2(root, targetSum, res);
return ans;
}
// Depth-first search + Each recursion generates a new set , Guaranteed not to interfere with other recursive branches
private void pathSum2(TreeNode root, int targetSum, LinkedList<Integer> res) {
if (root == null) return;
// Every time the recursion comes in, it will re new A collection , This ensures that the parameters res Does not interfere with each other in each recursion , There is no need to go back
LinkedList<Integer> temp = new LinkedList<>(res);
temp.add(root.val);
if (root.left == null && root.right == null) {
if (root.val == targetSum) {
ans.add(temp);
}
}
pathSum2(root.left, targetSum - root.val, temp);
pathSum2(root.right, targetSum - root.val, temp);
}
LeetCode Time consuming :5ms
It can be seen that time and space have increased a lot
- summary
- About recursion and backtracking , There are some introductions here that can deepen our understanding
link - There are two ways to solve the branch pollution problem :
The first one is : to flash back
The second kind : Each recursion creates a new object
边栏推荐
- [leetcode] intersecting linked list
- Project_ Visual analysis of epidemic data based on Web Crawler
- 2.1、ROS+PX4仿真---定点飞行控制
- Linux Installation MySQL database details
- Daily problem essay | 21.11.29: use resttemplate to call external put request, and prompt '400 bad request'
- [ongoing update...] 2021 National Electronic Design Competition for college students (III) interpretation of the anonymous four axis space developer flight control system design
- 视频压缩数据集TVD
- 關於概率統計中的排列組合
- 1.6 Px4 initialization calibration
- Leetcode 652 find duplicate subtrees (recommended by DFS)
猜你喜欢
![[ROS introduction] cmakelist Txt and packages XML interpretation](/img/26/bae82a457fb83b2214d2f8c20955e2.jpg)
[ROS introduction] cmakelist Txt and packages XML interpretation

On permutation and combination in probability and statistics
![[cloud native | kubernetes] actual combat of ingress case](/img/99/1674f79e7ade0ec2f39e9b2c522d59.png)
[cloud native | kubernetes] actual combat of ingress case

ROS参数服务器

【错误记录】Android 应用安全检测漏洞修复 ( StrandHogg 漏洞 | 设置 Activity 组件 android:taskAffinity=““ )

2021-02-27MATLAB的图像处理

A tutorial on building a website from scratch with complete steps (7000 words and 102 screenshots for everyone to understand, with source code attached)

Threejs: streamer effect encapsulation

1.5、PX4载具选择

Garbled code when the command parameter contains% in VisualStudio debugging
随机推荐
PX4从放弃到精通(二十四):自定义机型
There is a problem with numpy after CONDA installs pytoch
Digital IC Design self-study ing
LeetCode 1010 Pairs of Songs With Total Durations Divisible by 60 (hash)
A brief history of neural network
PX4装机教程(六)垂起固定翼(倾转)
2021-7-18 ROS notes XML language related
神经网络极简史,神经网络知识点整理
小包子关于分红的思考
Leetcode 1248 count number of nice subarrays
Loki learning summary (1) -- the best choice of Loki small and medium-sized project log system
OCR文字识别经典论文详解
[ROS introduction] cmakelist Txt and packages XML interpretation
如何下载网页照片
1.7 calibration of Px4 remote controller
threejs:流光效果封装
[geometric vision] 4.2 piecewise linear transformation
On permutation and combination in probability and statistics
Matlab array other common operation notes
[linked list] find the midpoint of the linked list and deepen the understanding and Application