遞歸:在一個方法的內部,對自身進行調用,又叫遞歸調用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;
}
}