递归(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);
    }
}
相关推荐
I_belong_to_jesus4 分钟前
C++关于分支预测的优化1
开发语言·c++·算法
Code_Solitude7 小时前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
上海潭龙东海科技有限公司7 小时前
客运站管控之动态孪生技术方案(新增一屏管控模块
数据仓库·人工智能·算法·重构·动态规划
YLCHUP10 小时前
【思维&图论建模】题解:债权(debt)_图论_建模_思路转化_思维题目_C++算法竞赛
c++·笔记·算法·数学建模·贪心算法·深度优先·图论
思麟呀10 小时前
背包DP(01背包+完全背包)
c++·算法
笑容掩饰我的失落11 小时前
区块链从小白到精通(七):Solidity 语法精讲——数据类型、函数、修饰器与事件
算法·区块链·php·智能合约·哈希算法
Pniubi12 小时前
力扣24. 两两交换链表中的节点(递归)
算法·leetcode·链表
꧁细听勿语情꧂13 小时前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
俊俊几年的13 小时前
动态规划(Dynamic Programming)详解:从入门到 LeetCode Hot 100
linux·c++·算法·leetcode·嵌入式·动态规划·c