递归

Open Link

递归

一个函数调用其自身就是递归

例题

1. 求n的阶乘的递归函数

int F(int n){
    if(n == 0){
        return 1;
    }
    return n * F(n - 1);
}

https://onlinegdb.com/rkUmBRb0v

2. 汉诺塔

void Hanoi(int n, char src, char mid, char dest){
    if( n == 1){
        cout << src <<" -> "<< dest <<endl;
        return;
    }
    Hanoi(n-1, src, dest, mid);
    cout << src <<" -> "<< dest <<endl;
    Hanoi(n-1, mid, src, dest);
    return;
}

https://onlinegdb.com/By2l_C-AP

3. N皇后


4. 斐波那契

#include <stdio.h>
#include <iostream>
#include <cmath>
using namespace std;
int F(int n){
    if( n <= 1){
        return n;
    }
    return F(n - 2) + F(n - 1);
}
int main(){
    int n;
    cin >> n;
    cout << F(n);
    return 0;
}

https://onlinegdb.com/rJfHDWM0w


    昵称
    邮箱
    博链
    评论