递归思想-从入门到入土

本文最后更新于:2 小时前

计算n的阶乘

#include <iostream>
using namespace std;
//阶乘
unsigned fac(unsigned n) {
    unsigned f;
    if (n == 0) {
        f = 1;
    }
    else {
        f = fac(n - 1) * n;
    }
    return f;
}


int main()
{
    unsigned n;
    cout << "Enter a positive integer: ";
    cin >> n;
    unsigned y = fac(n);
    cout << n << "! = " << y << endl;
    return 0;
}

n个人里面选c个人

#include <iostream>
using namespace std;

int comm(int n, int k) {
    if (k > n) {
        return 0;
    }
    else if (n == k || k == 0) {
        return 1;
    }
    else {
        return comm(n - 1, k) + comm(n - 1, k - 1);
    }
}


int main()
{
    int n, k;
    cout << "Please enter two integers n and k:";
    cin >> n >> k;
    cout << "C(n,k) = " << comm(n, k) << endl;
    return 0;
}

汉诺塔

#include <iostream>
using namespace std;

void move(char src, char dest) {
    cout << src << "-->" << dest << endl;
}

void hanoi(int n, char src, char medium, char dest) {
    if (n == 1) {
        move(src, dest);
    }
    else {
        hanoi(n - 1, src, dest, medium);
        move(src, dest);
        hanoi(n - 1, medium, src, dest);
    }
}

int main()
{
    int m;
    cout << "Enter the number of diskes:";
    cin >> m;
    cout << "the steos to moving " << m << " diskes:" << endl;
    hanoi(m, 'A', 'B', 'C');
    return 0;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!