递归调用

递归:在一个方法的内部,对自身进行调用,又叫递归调用spa

循环和递归都要具备三部分:初始值,终止条件,前进步长递归

递归和迭代是等价的ci

常见的问题:累加加和(累乘乘积),汉诺塔,斐波那契数列it

public class Recuresion_06 {io

public static void main(String[] args) {class

// TODO Auto-generated method stub循环

System.out.println(factorial(10));方法

System.out.println("!!!!!!!!!!!!!!!!!!!");im

System.out.println(fibonacci(10));static

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;

}

}

相关文章
相关标签/搜索