java中的迭代和递归

迭代和递归

递归是重复调用函数自身实现循环, 迭代是函数内某段代码实现循环。递归总体来说更容易理解,代码简
洁 ,但 是很容易栈溢出,并且费时,迭代的话,代码看起来不是很好理解,但是运行速度快。

场景

最经典的情景是就走台阶,一次只能走一个或者两个,问有多少种走法,在这里就可以使用迭代或者递归完成

图解

在这里插入图片描述

使用递归来完成
/**
 * @author 理想
 * @version 1.0
 * @date 2021/7/7 14:15
 */
public class 递归 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println(method(40)); //165580141
        long end = System.currentTimeMillis();
        System.out.println(end-start);  //387

    }
    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);
    }
}

使用迭代来完成
/**
 * @author 理想
 * @version 1.0
 * @date 2021/7/7 14:27
 */
public class 迭代 {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        System.out.println(method(40));// 165580141
        long end = System.currentTimeMillis();
        System.out.println(end-start);

    }
    public static int method(int n)
    {
        int one=1; //相当于f(n-2)
        int two=2; //相当于f(n-1)
        int sum=0;
        if (n<1)
        {
            throw new RuntimeException("你输入的值不合适");
        }
        if (n==1||n==2)
            return n;
            //靠for循环来完成
        for(int i=3;i<=n;i++)
        {
        //第一次这里相当于sum=f(3)
            sum=one+two; //sum=1+2=f(3)
            one=two;  //one=f(2)
            two=sum;  //two=f(3)    然后新一轮 i=4  sum=f(2)+f(3)=f(4)   就这样不断循环
         }
        return sum;

    }
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值