简单递归
面对递归算法,最重要的是出口,如何寻找出口。
1. n!
划定范围后,找出口,出口就在当 n1 或者 n0时。
public static int getJC(int n){
if(n<0){
throw new Exception("参数非法");
}
if(n==1||n==0){
return 1;
}
return getJC(n-1)*n;
}
2. 斐波那契数列
1 1 2 3 5 8 13 下一项是前两项之和 从第三个开始,也就是说出口在 1 和2
public static int getJC(int n){
if(n<=0){
throw new Exception("参数非法");
}
if(n==1||n==2){
return 1;
}
return getJC(n-1)+getJC(n-2);
}