zoukankan      html  css  js  c++  java
  • 线性递归和尾递归

    尾递归调用的时候不用在栈中保存之前运算的值,相比线性递归就节省了栈资源。比如计算阶乘:

    线性递归:

        public int rescuvie(int i){
            return i>1 ? i * rescuvie(i-1) : 1;
        }

    尾递归:

        public int rescuvie(int i,int a){
            return i>1 ? rescuvie(i-1,a*i) : 1;
        }

    尾递归计算5的阶乘,直接调用rescuvie(5,1)

    尾递归的作用:

    对于线性递归,它的递归过程:

    {5 * Rescuvie(4)}
    {5 * {4 * Rescuvie(3)}}
    {5 * {4 * {3 * Rescuvie(2)}}}
    {5 * {4 * {3 * {2 * Rescuvie(1)}}}}
    {5 * {4 * {3 * {2 * 1}}}}
    {5 * {4 * {3 * 2}}}
    {5 * {4 * 6}}
    {5 * 24}
    120
    对于尾递归,它的递归过程:
    rescuvie(5)
    rescuvie(5, 1)
    rescuvie(4, 5)
    rescuvie(3, 20)
    rescuvie(2, 60)
    rescuvie(1, 120)
    120
    所以线性递归运行的过程中,要存之前计算得出的值放在堆栈里。如果使用尾递归,可以节省栈资源
  • 相关阅读:
    HashMap和Hashtable的区别
    装箱以及拆箱
    泛型
    LinkedList和ArrayList异同
    ArrayList的输出方式以及ArrayList的因子增长数
    limit的优化
    mysql五大数据引擎的分别
    ios
    css3(1)
    php
  • 原文地址:https://www.cnblogs.com/hithlb/p/4517114.html
Copyright © 2011-2022 走看看