zoukankan      html  css  js  c++  java
  • C 递归与尾递归

    递归(Recursion)

    栈(Stack)

    • 先进后出(FILO, First In Last Out)
    • 满足了函数调用(Call)和返回(Return)的顺序
    • 需要维护每个函数调用信息直到返回后才释放,占用内存大

    递归函数

    • 基线条件(Base Condition)
    • 递归条件(Recursive Condition)
    // factorial.c
    #include <stdio.h>
    
    int fact(int n) 
    {
        if (n < 0)
            return 0;
        else if (n == 1 || n == 0)
            return 1;
        else
            return n-- * fact(n);
    }
    
    int main(void) 
    {
        for (int i = -1; i <= 10; i++)
            printf("%d! = %d
    ", i, fact(i));
    
        return 0;
    }
    

    尾递归

    • 解决递归占用内存大的问题
    • 函数中所有递归形式的调用都出现在函数的末尾
    • 当递归调用是整个函数体中最后执行的语句且它的返回值不属于表达式的一部分是,这个递归调用就是尾递归
    • 回归过程不做任何操作
    • 当编译器检测到一个函数调用是尾递归的时候,它就覆盖当前的活跃记录而不是在栈中创建一个新的
    // factorial.c
    #include <stdio.h>
    
    /* a初始化为1 */
    int fact(int n, int a)
    {
        if (n < 0)
            return 0;
        else if (n == 0)
            return 1;
        else if (n == 1)
            return a;
        else
            return fact(n - 1, n * a);
    }
    
    int main(void) 
    {
        for (int i = -1; i <= 10; i++)
            printf("%d! = %d
    ", i, fact(i, 1));
    
        return 0;
    }
  • 相关阅读:
    多项式全家桶学习笔记
    [题解] Luogu P2000 拯救世界
    [题解] LuoguP4389 付公主的背包
    [题解] CF438E The Child and Binary Tree
    拉格朗日插值法
    bzoj2788: [Poi2012]Festival
    暑假集训test-8-29
    luoguP4768 [NOI2018]归程
    HDU6331Problem M. Walking Plan
    暑假集训test-8-28
  • 原文地址:https://www.cnblogs.com/noonjuan/p/12102547.html
Copyright © 2011-2022 走看看