一、递归
(1)、概述
递归 : 就是在当前方法中,调用自己(当前方法)
基本思想 : 以此类推
递归和迭代是等价的,而迭代就是循环,所以递归也是重复做某件事 三要素 : 初始值,终止条件,步长
如果循环能做到的,就不要使用递归,因为递归效率低,比较耗费内存
应用场景 :
一般树状结构,需要使用递归来完成 比如菜单目录,每一层目录结构,都是一个循环,两层就需要嵌套循环,比如不知道有多少子目录结构呢? 循环就不行了
(2)、常见异常
public class Recursion_01 {
public static void main(String[] args) {
m1();
}
public static void m1() {
// 没有终止条件
m1();
}
}

(3)、案例
public class Recursion_02 {
public static void main(String[] args) {
int result = sum(5);
System.out.println(result);
}
// 计算1-N的加和,返回相加结果
public static int sum(int n) {
if (n == 1) {
return 1;
} else {
return n + sum(n - 1);
}
}
}
/**
* 斐波那契数列
*
* 前两位都是1,以后每一位都是前两位的和
*
* 1,1,2,3,5,8,13,21,34,55,89....
*
* 需求 : 传入位数,判断对应位数上 的值是多少
*
*/
public class Recursion_03 {
static int count = 0;
public static void main(String[] args) {
try {
long result = fibonacci(2222222);
System.out.println(result);
} catch (Error e) {
}
System.out.println(count);
System.out.println(fibInteration(60));
}
public static long fibonacci(int n) {
count++;
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
public static long fibInteration(int n) {
if (n < 1) {
System.out.println("有病");
return -1;
}
// 默认表示第一位(也表示当前为的前两位)
long a = 1;
// 默认表示第二位(也表示当前为前一位)
long b = 1;
long c = 1;
for (int i = 3; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
91

被折叠的 条评论
为什么被折叠?



