这两题必须要能手写出来
求N的阶乘
这道算法题一般考查的递归的编程技能,那么我们回顾下递归程序的特点:
1,什么是递归?
递归,就是方法内部调用方法自身
递归的注意事项:
找到规律,编写递归公式
找到出口(边界值),让递归有结束边界
注意:如果递归太多层,或者没有正确结束递归,则会出现“栈内存溢出Error”!
问题:为什么会出现栈内存溢出,而不是堆内存溢出?
2,这道题该怎么写?
规律:N!=(n-1)!*n;
出口:n==1或n==0 return 1;
public static int getResult(int n){
if(n<0){
throw new ValidateException("非法参数");
}
if(n==1 || n==0){
return 1;
}
return getResult(n-1)*n;
}
不是有递归:
public int doFactorial(int n){
int result = 1;
if(n<0){
return -1;//返回-1,说明传入数据不合法
}
if(n==0){
return 1;
}
for(int i =1;i<=n;i++){
result*=i;
}
return result;
}
求解斐波那切数列的第N个数是几
如何实现递归求斐波那切数列第N个数字的值(传说中的不死神兔就是这个问题)
数字的规律:1,1,2,3,5,8,13,21....
所以,我们可以分析编写如下:
规律:每个数等于前两个数之和
出口:第一项和第二项都等于1
//时间复杂度O(2^n)
public static int fib1(int n) {
if(n < 0) {
return -1;
}
if(n==1 || n==2) {
return 1;
} else {
return fib1(n-1) + fib1(n-2);
}
}
//时间复杂度O(n)
public static int fib2(int n) {
if(n < 0) {
return -1;
}
if(n==1 || n==2) {
return 1;
} else {
int first = 1;
int second = 1;
while(n -- > 2) {
second += first;
first = second - first;
}
return second;
}
}