迭代和递归
递归是重复调用函数自身实现循环, 迭代是函数内某段代码实现循环。递归总体来说更容易理解,代码简
洁 ,但 是很容易栈溢出,并且费时,迭代的话,代码看起来不是很好理解,但是运行速度快。
场景
最经典的情景是就走台阶,一次只能走一个或者两个,问有多少种走法,在这里就可以使用迭代或者递归完成
图解
使用递归来完成
public class 递归 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(method(40));
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static int method(int n)
{
if(n<1)
{
throw new RuntimeException("你输入的值不合适");
}
if (n==1||n==2)
{
return n;
}
return method(n-1)+method(n-2);
}
}
使用迭代来完成
public class 迭代 {
public static void main(String[] args) {
long start = System.currentTimeMillis();
System.out.println(method(40));
long end = System.currentTimeMillis();
System.out.println(end-start);
}
public static int method(int n)
{
int one=1;
int two=2;
int sum=0;
if (n<1)
{
throw new RuntimeException("你输入的值不合适");
}
if (n==1||n==2)
return n;
for(int i=3;i<=n;i++)
{
sum=one+two;
one=two;
two=sum;
}
return sum;
}
}