【数据结构】郝斌数据结构——笔记06

递归 Recursion

定义:

一个函数,直接或者间接的调用给自己

要求:

必须要有明确的中止条件

处理的数据规模在递减

转化必须是可解的

循环和递归的区别:

递归:

1、难理解

2、速度慢

3、存储空间占用大

循环

1、易理解

2、速度快

3、存储空间占用小

应用:

数和森林

数和图的算法

数学公式

死递归样例:

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

void funcA(int * pCounter);
void funcB(int * pCounter);
void funcC(int * pCounter);

int main() {
    int counter = 1;
    funcA(&counter);
    return 0;
}

void funcA(int * pCounter) {
    ++ *pCounter;
    printf("funcA been called, counter is %d
", *pCounter);
    funcB(pCounter);
}

void funcB(int * pCounter) {
    ++ *pCounter;
    printf("funcB been called, counter is %d
", *pCounter);
    funcC(pCounter);
}

void funcC(int * pCounter) {
    ++ *pCounter;
    printf("funcC been called, counter is %d
", *pCounter);
    funcA(pCounter);
}

运行结果:

counter变量设置为1,到43179时,程序结束了

也就是说函数调用最多至43178次

funcB been called, counter is 43179

Process finished with exit code -1073741571 (0xC00000FD)

案例2:

这样是直接调用自己来实现递归

#include <stdio.h>

void func(int n) {
    if (n == 1) printf("func is end
");
    else func(n - 1);
}

int main() {
    func(4);
    return 0;
}

案例3:

阶乘递归实现

#include <stdio.h>

long func(long number) {
    if (number == 1) return 1;
    return func(number - 1) * number;
}

int main() {
    printf("%d
", func(12));
    return 0;
}

  

案例4:

叠加求和至100

#include <stdio.h>

long sum(int number) {
    if (number == 1) return 1;
    return number + sum(number - 1);
}

int main() {
    printf("%d
", sum(150));
    return 0;
}

  

汉诺塔问题:

原文地址:https://www.cnblogs.com/mindzone/p/14621533.html