C++中楊輝三角形的遞歸實(shí)現(xiàn)

c++
小樊
87
2024-07-05 19:10:20

#include <iostream>

int pascal(int row, int col) {
    if (col == 0 || col == row) {
        return 1;
    } else {
        return pascal(row - 1, col - 1) + pascal(row - 1, col);
    }
}

void printPascal(int numRows) {
    for (int i = 0; i < numRows; i++) {
        for (int j = 0; j <= i; j++) {
            std::cout << pascal(i, j) << " ";
        }
        std::cout << std::endl;
    }
}

int main() {
    int numRows;
    std::cout << "Enter the number of rows for Pascal's Triangle: ";
    std::cin >> numRows;
    
    printPascal(numRows);
    
    return 0;
}

這段代碼實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的遞歸版本的楊輝三角形生成器。用戶可以輸入一個(gè)整數(shù),程序?qū)⑸蓪?duì)應(yīng)行數(shù)的楊輝三角形并輸出到控制臺(tái)上。

0