递归结构1

自己调用自己,需要有一个递归头,表示什么时候不调用

/**
 * 测试递归
 */
public class TestDiGui {
    public static int num = 10;
    public static void a() {
        num--;
        System.out.println("Test01:"+num);
        if (num>0) {
            a();
        }
    }
    public static void main(String[] args) {
        a();
    }
}

运行结果
Test01:9
Test01:8
Test01:7
Test01:6
Test01:5
Test01:4
Test01:3
Test01:2
Test01:1
Test01:0

简单的程序是递归调用的优点之一

/**
 * 测算n的阶乘
 */
public class TestDiGui02 {
    static long factorial(int n){
       if (n==1){
           return 1;
       }else {
           return n*factorial(n-1);
       }
   }
    public static void main(String[] args) {
        long d1 = System.currentTimeMillis();
        long result = factorial(10);
        long d2 = System.currentTimeMillis();
        System.out.println("阶乘的结果:"+result);
        System.out.println("耗时:"+(d2-d1));
    }
}


运行结果
阶乘的结果:3628800
耗时:0

缺点是会占用大量的系统堆栈,内存耗用多。

/**
 * 测算斐波那契数列
 */
public class TestFib12 {
    public static int Fib(int n) {
        if(n<=2){
            return n;
        }else {
            return Fib(n-1)+Fib(n-2);
        }
    }
    public static void main(String[] args) {
        int a = 10;
        long d1 = System.currentTimeMillis();
        for (int i=0;i<=10;i++) {
            System.out.println("F("+i+")="+Fib(i));

        }
        long d2 = System.currentTimeMillis();
        System.out.println("耗时:"+(d2-d1));

    }
}

运行结果
F(0)=0
F(1)=1
F(2)=2
F(3)=3
F(4)=5
F(5)=8
F(6)=13
F(7)=21
F(8)=34
F(9)=55
F(10)=89
耗时:12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值