对于递归的调用主要是自己调用自己的意思。可以通过下图来理解递归调用。
当需要求出 f5 的时候就需要调用 f4 与 f3 ,在调用 f4 的时候就需要 f3 和 f2 。而f2 和f1 都是1.
下图中就需要用到递归调用。
方法如下:
package fabonacci.txx.com;
public class Fabonacci {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(func(7));
}
public static int func(int a){
if (a == 1 || a == 2){
return 1;
}else{
return func(a-1) + func(a-2);
}
}
}
但若要使用非递归来实现以上要求的话。可以用下面的方法来求
package fabonacci.txx.com;
public class FabonacciFor {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(func(5));
}
public static int func(int n){
if(n == 1 || n ==2 ){
return 1;
}
int f1 = 1;
int f2 = 1;
int f = 0;
for(int i = 1; i<=n-2 ;i++){
f = f1 + f2;
f1 = f2;
f2 = f;
}
return f;
}
}