递归(Recursion)

递归

For some types of problems, it is useful to have functions call themselves. A recursive function is a function that calls itself either directly or indirectly through another function. Recursion is a complex topic discussed at length in upper-level computer science courses.

对于某些类型的问题,让函数调用自身很有用。 递归函数是直接或通过另一个函数间接调用自身的函数。 递归是高级计算机科学课程中详细讨论的一个复杂主题。

A recursive function is called to solve a problem. The function actually knows how to solve only the simplest case(s), or so-called base case(s) . If the function is called with a base case, the function simply returns a result. If the function is called with a more complex problem, the function divides the problem into two conceptual pieces: A piece that the function knows how to do and a piece that the function does not know how to do. To make recursion feasible, the latter piece must resemble the original problem, but be a slightly simpler or slightly smaller version of the original problem. Because this new problem looks like the original problem, the function launches (calls) a fresh copy of itself to go to work on the smaller problem --- this is referred to as recursive call and is also called the recursion step.

调用递归函数来解决问题。该函数实际上只知道如何解决最简单的情况,或所谓的基本情况。如果使用基本情况调用该函数,则该函数仅返回结果。如果针对更复杂的问题调用该函数,则该函数会将问题分为两个概念部分:函数知道如何执行的部分和函数不知道如何执行的部分。为了使递归可行,后一部分必须类似于原始问题,但是原始问题的稍微简单或稍微小的版本。因为这个新问题看起来像原始问题,所以该函数启动(调用)自身的新副本来处理较小的问题 --- 这称为递归调用 ,也称为递归步骤

斐波那契数定义:
F 0 = 0 F 1 = 1 F n = F n − 1 + F n − 2 ( n ≥ 2 , n ∈ N ) \begin{aligned} F_{0}&=0\\ F_{1}&=1\\ F_{n}&=F_{n-1}+F_{n-2}{\left(n\geq 2,n\in \mathbb{N} \right )} \end{aligned} F0F1Fn=0=1=Fn−1+Fn−2(n≥2,n∈N)

如下为递归获取第n个斐波那契数。

c 复制代码
#include <stdio.h>

unsigned long fibonacci(unsigned long n);

int main(int argc, char *argv[]) {
    unsigned long n = 0;
    printf("Enter an integer: ");
    scanf("%lu", &n);

    printf("%s%lu%s%lu\n",
            "Fibonacci(", n,
            ") = ", fibonacci(n));

    return 0;
}

unsigned long fibonacci(unsigned long n) {
    if (n == 0 || n == 1) {
        return n;
    } else {
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
}
相关推荐
AI科技星8 分钟前
万能学习方法论的理论建构与多领域适配性研究(乖乖数学)
人工智能·学习·算法·机器学习·平面·数据挖掘
Ashore11_21 分钟前
蓝桥杯16届Java研究生组
java·算法·蓝桥杯
6Hzlia24 分钟前
【Hot 100 刷题计划】 LeetCode 76. 最小覆盖子串 | C++ 滑动窗口题解
c++·算法·leetcode
像素猎人28 分钟前
蓝桥杯OJ2049蓝桥勇士【动态规划】【dp[n]不是符合题意的答案,只是以an结尾的子问题的答案】
c++·算法·蓝桥杯·动态规划·区间dp
羊小猪~~28 分钟前
LLM--SFT简介
python·考研·算法·ai·大模型·llm·微调
广州灵眸科技有限公司40 分钟前
瑞芯微(EASY EAI)RV1126B 人脸98关键点算法识别
开发语言·科技·嵌入式硬件·物联网·算法·php
篮子里的玫瑰44 分钟前
FreeRTOS:信号量与互斥量在DMA串口发送中的实战剖析
stm32·单片机·嵌入式硬件·算法
hughnz1 小时前
钻头技术持续突飞猛进:地热钻探领域的创新
人工智能·算法
xiaoye-duck1 小时前
《算法题讲解指南:动态规划算法--子数组系列》--21.乘积最大子数组,22.乘积为正数的最长子数组
c++·算法·动态规划
MicroTech20251 小时前
突破非幺正动力学瓶颈:MLGO微算法科技量子虚时演化赋能开放量子系统模拟
科技·算法·量子计算