当前位置:网站首页>Day10/11 recursion / backtracking
Day10/11 recursion / backtracking
2022-06-10 14:54:00 【Light parasitic in the dark】
1 21. Merge two ordered lists
1.1 subject

1.2 Answer key
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if(list1 == null)
return list2;
if(list2 == null)
return list1;
ListNode mergeList = new ListNode();
ListNode res = mergeList;
ListNode p = list1;
ListNode q = list2;
while(p != null && q != null){
if(p.val < q.val){
mergeList.next = p;
mergeList = mergeList.next;
p = p.next;
}else{
mergeList.next = q;
mergeList = mergeList.next;
q = q.next;
}
}
if(p == null && q == null)
return res;
while(p != null){
mergeList.next = p;
mergeList = mergeList.next;
p = p.next;
}
while(q != null){
mergeList.next = q;
mergeList = mergeList.next;
q = q.next;
}
return res.next;
}
}
notes : The idea of merging adopted by oneself , But the problem itself is more appropriate to do it in a recursive way , Of this article Answer key very good .
2 206. Reverse a linked list
2.1 subject

2.2 Answer key
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null)
return head;
ListNode p = new ListNode(head.val, null);
while(head.next != null){
ListNode q = new ListNode(head.next.val, null);
q.next = p;
p = q;
head = head.next;
}
return p;
}
}
notes : The first idea is to insert the head , It has also been realized. ; Looked at the Answer key , Recursion is so important .
3 77. Combine
3.1 subject

3.2 Answer key
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if(k <= 0 || k > n)
return res;
// from 1 Begin your search
Deque<Integer> path = new ArrayDeque<>();
dfs(n, k, 1, path, res);
return res;
}
private void dfs(int n, int k, int begin, Deque<Integer> path, List<List<Integer>> res){
// Determine the termination condition of recursion : When the stack length reaches the combined length
if(path.size() == k){
res.add(new ArrayList<>(path));
return;
}
// Traverse all search starting points
for(int i = begin; i <= n - (k - path.size()) + 1; i++){
// Add a number to the path variable
path.addLast(i);
// Next round of search , Set the search starting point to add 1, Because duplicate elements are not allowed in Combinatorial Mathematics
dfs(n, k, i + 1, path, res);
// Focus on understanding here : Depth first traversal has a backward process , So what did you do before recursion , After recursion, you need to do the reverse operation of the same operation
path.removeLast();
}
}
}
notes : This big guy's Backtracking problem solving Study hard .
4 46. Full Permutation
4.1 subject

4.2 Answer key
class Solution {
public List<List<Integer>> permute(int[] nums) {
int len = nums.length;
List<List<Integer>> res = new ArrayList<>();
if(len == 0)
return res;
// Record the prime progression of each permutation path Information about
boolean[] used = new boolean[len];
List<Integer> path = new ArrayList<>();
dfs(nums, len, 0, path, used, res);
return res;
}
private void dfs(int[] nums, int len, int depth, List<Integer> path, boolean[] used, List<List<Integer>> res){
// Recursive termination condition :depth==len, That is to say, all the numbers have been taken
if(depth == len){
res.add(new ArrayList<>(path));
return;
}
// Among the unselected numbers, select one element in turn as the element of the next position
for(int i = 0; i < len; i++){
// If the element does not enter path
if(!used[i]){
path.add(nums[i]);
used[i] = true;
// Continue to drill down until path Until it's full
dfs(nums, len, depth + 1, path, used, res);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
}
notes : Answer key Take a good look at .
5 784. All the letters are in uppercase and lowercase
5.1 subject

5.2 Answer key
class Solution {
public List<String> letterCasePermutation(String s) {
List<String> res = new ArrayList<>();
char[] path = new char[s.length()];
dfs(0, s.toCharArray(), res);
return res;
}
private void dfs(int index, char[] s, List<String> res){
if(index == s.length){
res.add(new String(s));
return;
}
if(Character.isLetter(s[index])) {
// use Character.isLetter() Decide if it's a letter , Very convenient
s[index] = Character.toLowerCase(s[index]);
dfs(index + 1, s, res); // For both cases where letters are guaranteed to be lowercase and uppercase
s[index] = Character.toUpperCase(s[index]);
} // Use them separately Character.toLowerCase() and Character.toUpperCase() Convert upper and lower case letters , There is no need to write judgment to convert manually
dfs(index + 1, s, res); // Both numbers and letters go to the next character
}
}
notes : The details of this problem are not clear , Answer key Here it is .
6 summary
It feels like whether it's a recursion or a backtracking problem , There are certain templates , Come back to review these questions after brushing all the questions , Sharp brush of the same type .
边栏推荐
- JS get the maximum value in the array
- Google Earth Engine(GEE)——基于s2影像的实时全球10米土地利用/土地覆盖(LULC)数据集
- Wechat applet closes the current page
- Collision detection unity experiment code
- 信息论与编码2 期末复习-BCH码
- 【LogoDetection 数据集处理】(3)将训练集按照类别划分为多个文件夹
- js获取数组中最大值
- 共创地市价值空间,2022年华为商业分销地市百城行·宁波站成功举办
- 佳博GP2120TU标签打印机 安装和使用教程(PC)
- 2022南京国际智慧工地装备展览会
猜你喜欢

AutoRunner自动化测试工具如何创建项目-Alltesting|泽众云测试

利用 GDB 快速阅读 postgresql 的内核代码

CVPR 2022 | frame by frame motion representation of long video based on sequence contrast learning

How can JMeter parameterization be implemented?

AutoCAD - set text spacing and line spacing

Detailed explanation of binary search
![[logodetection data set processing] (2) draw the label box of the training set picture](/img/66/6c19b80b99d1e3ce50bac439e0e903.jpg)
[logodetection data set processing] (2) draw the label box of the training set picture

Flutter listview, column, row learning personal summary 2

共创地市价值空间,2022年华为商业分销地市百城行·宁波站成功举办

【大咖秀】博睿数据眼中的AIOps,选择正确的赛道正确的人
随机推荐
Gin blog summary 1
Singleton pattern and special class design
One-way hash function
【云原生 | Kubernetes篇】深入RC、RS、DaemonSet、StatefulSet(七)
远程监控及数据采集解决方案
小程序网络请求Promise化
what‘t the meaning of “de facto“
LeetCode_20(括号匹配)
Generate a dataset of training vectors for doc2vec
4、再遇Panuon.UI.Silver之窗体标题栏
小程序警告:Now you can provide attr `wx:key` for a `wx:for` to improve performance.
How to implement the association between interfaces in JMeter?
产品开发的早期阶段,是选择开发app还是小程序?
Applet network request promise
小程序实现全局数据共享
AutoCAD - set text spacing and line spacing
【报名】解决科技创业者核心关切,「星云计划公开课」线上招生开启
WordPress的管理员用户名是如何泄露的
Flutter Icon Stack LIsttitle... Learning summary 3
2022第十四届南京国际人工智能产品展会