一.前言
递归就是把一个大的问题分解成最小的一个模型,然后不断的调用他来解决这个大问题。
成熟的算法基本上都依靠递归来解决。
1.2 数组求和展示递归
不断地相加,来解决递归的问题。
public static int sum(int[] arr){
return sum(arr,0);
}
private static int sum(int[] arr,int l){
if(l == arr.length){
return 0;
}
return arr[l] + sum(arr,l + 1);
}
public class Sum{
public static int sum(int[] arr){
return sum(arr,0);
}
//计算arr[l...n)这个区间诶所有数字的和
private static int sum(int [] arr ,int l){
if(l == arr.length)
return 0;
return arr[l] + sum(arr,l+1);
}
}
二.Recursion in List
2.3 链表中的递归
链表本身天然就有一个递归的性质
递归解决203删除指定元素
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return null;
ListNode res = removeElements(head.next,val);
if(head.val == val)
return res;
else{
head.next = res;
return head;
}
}
}
2.4 递归函数的微观解读
系统栈函数调用
递归调用就是函数自己调用自己
2.5 leetcode 203 递归
* Given the head of a linked list and an integer val,
* remove all the nodes of the linked list that has Node.val == val,
* and return the new head.
6--->7--->8--->null
public ListNode removeElements(ListNode head , int val){
if(head == null)
return null;
head.next = removeElements(head.next,val);
return head.val == val ? head.next : head;
}
2.6 debug recursion
package eLinkedList.fRecursion.debug;
public class Solution {
public ListNode removeElements(ListNode head, int val, int depth) {
String depthString = generateDepthString(depth);
System.out.print(depthString);
System.out.println("Call: remove " + val + " in " + head);
if(head == null){
System.out.print(depthString);
System.out.println("Return: " + head);
return head;
}
ListNode res = removeElements(head.next, val, depth + 1);
System.out.print(depthString);
System.out.println("After remove " + val + ": " + res);
ListNode ret;
if(head.val == val)
ret = res;
else{
head.next = res;
ret = head;
}
System.out.print(depthString);
System.out.println("Return: " + ret);
return ret;
}
private String generateDepthString(int depth){
StringBuilder res = new StringBuilder();
for(int i = 0 ; i < depth ; i ++)
res.append("--");
return res.toString();
}
public static void main(String[] args) {
int[] nums = {1, 2, 6, 3, 4, 5, 6};
ListNode head = new ListNode(nums);
System.out.println(head);
ListNode res = (new Solution()).removeElements(head, 6, 0);
System.out.println(res);
}
}
2.7 双链表
方便遍历查找
2.8 循环链表
向链表结尾添加 O(1)
2.9 数组链表
对于已知Element个数的情况下,用数组链表可能更好