1.认识 |
- 递归调用是一种特殊的嵌套调用,是某个函数调用自己或者是调用其他函数后再次调用自己的,只要函数之间互相调用能产生循环的则一定是递归调用,递归调用一种解决方案,一种是逻辑思想。
- 分析
分析程序从main方法开始分析
main方法从上到下,调用method5方法,method5会调用method4…一直调用method1,调用完成再返回
2.实例 |
public class Test{
public static void main(String arg[]){
System.out.println(f(5));
}
public static int f(int n){
if(n == 1||n==2){
return 1;
}else{
return f(n-1) + f(n-2);
}
}
}
- 分析
- 用非递归方式解决上述问题
public class Fab{
public static void main(String[] args){
System.out.println(f(40));
}
public static long f(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;
}
return f;
}
}
- 执行结果
3.小结 |
- 多看别人的代码,看的多了才能设计自己的
- 多分析,分析的多了明白的更透彻
- 然而。。。