递归
1.递归式一种常见的算法思路,在很多算法中都会用到。比如:深度优先搜索(DFS:Depth First Search)等。
2.递归的基本思想就是“自己调用自己”
递归结构包括两个部分:
一,定义递归头。解决:什么时候不调用自身方法。如果没有头,将陷入死循环,也就是递归的结束条件。
二,递归体。解决:什么时候需要调用自身方法。
使用递归求n的示例!
/**
测试递归
*/
public class Test1{
public static void main(String[] args){
long result = factorial(5);
System.out.println(result);
}
//阶乘:5*4*3*2*1
public static long factorial(int n){
if(n==1){
return 1;
}else{
return n*factorial(n-1);
}
}
}
递归的缺陷
算法简单的是递归的有点之一。但是递归调用会占用大量的系统堆栈,内存耗用多,再递归调用层次多的时速度要比循环慢得多,所以在使用递归时要慎重。
public class Test2{
public static void main(String[] args){
long startTime = System.currentTimeMillis(); //当前时刻
long result = factorial(5);
long endTime = System.currentTimeMillis(); //当前时刻
System.out.println(result);
System.out.println("递归耗时:"+(endTime-startTime));
}
public static long factorial(int n){
if(n==1){
return 1;
}else{
return n*factorial(n-1);
}
}
}
比如下面的递归耗时,但用普通循环的话快得多!
public class Test23{
public static void main(String[] args){
long d3 = System.currentTimeMillis();
int a = 10;
int result = 1;
while(a>1){
result *= a*(a-1);
a -= 2;
}
long d4 = System.currentTimeMillis();
System.out.println(result);
System.out.println("普通循环费时:%s%n",d4-d3);
}
}