什么是递归
本质上,将原来的问题,转化为更小的同一问题,递归实际上也和普通函数调用一样,只不过调用的是函数自身。
满足递归的2个条件:
1. 自身调用,通过自身调用来逐步缩小问题的规模
2. 递归出口,存在一种简单条件,能够让该方法退出
合理地使用递归能够大大简化我们的程序代码,但是递归调用也是有代价的:函数调用会使用系统栈空间,频繁的函数调用会给系统栈空间带来额外的开销。
下面是递归使用的2个例子
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);
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8};
System.out.println(sum(nums));
}
}
2. 删除链表中的特定元素
Solution.java
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null)
return head;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
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);
System.out.println(res);
}
}
ListNode.java
public class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
// 链表节点的构造函数
// 使用arr为参数,创建一个链表,当前的ListNode为链表头结点
public ListNode(int[] arr){
if(arr == null || arr.length == 0)
throw new IllegalArgumentException("arr can not be empty");
this.val = arr[0];
ListNode cur = this;
for(int i = 1 ; i < arr.length ; i ++){
cur.next = new ListNode(arr[i]);
cur = cur.next;
}
}
// 以当前节点为头结点的链表信息字符串
@Override
public String toString(){
StringBuilder s = new StringBuilder();
ListNode cur = this;
while(cur != null){
s.append(cur.val + "->");
cur = cur.next;
}
s.append("NULL");
return s.toString();
}
}