递归调用
递归:在一个方法的内部,对自身进行调用,又叫递归调用
循环和递归都要具有三部分:初始值,终止条件,前进步长
递归和迭代是等价的
常见的问题:累加加和(累乘乘积),汉诺塔,斐波那契数列
public class Recuresion_06 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(factorial(10));
System.out.println("!!!!!!!!!!!!!!!!!!!");
System.out.println(fibonacci(10));
System.out.println("!!!!!!!!!!!!!!!!!!!");
System.out.println(fibIteration(5));
}
// 阶乘:factorial
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
System.out.print(n + "*" + (n - 1) + ",");
return n * factorial(n - 1);
}
}
// 斐波那契数列
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
System.out.print((n - 1) + "+" + (n - 2) + ",");
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
// 斐波那契数列,迭代实现;iteration
public static long fibIteration(int index) {
if (index == 1 || index == 2) {
return 1;
}
long f1 = 1l;
long f2 = 1l;
long f = 0;
for (int i = 0; i < index-2; i++) {
f = f1 + f2;
f1 = f2;
f2 = f;
System.out.print(f2 + "+" + f1 + ",");
}
return f;
}
}