溫馨提示×

C++楊輝三角形的迭代實現(xiàn)方法

c++
小樊
85
2024-07-05 19:19:29
欄目: 編程語言

#include <iostream>
using namespace std;

void printPascalTriangle(int n) {
    int dp[n][n];
    
    for (int i = 0; i < n; i++) {
        dp[i][0] = 1;
        dp[i][i] = 1;
    }
    
    for (int i = 2; i < n; i++) {
        for (int j = 1; j < i; j++) {
            dp[i][j] = dp[i-1][j-1] + dp[i-1][j];
        }
    }
    
    for (int i = 0; i < n; i++) {
        for (int j = 0; j <= i; j++) {
            cout << dp[i][j] << " ";
        }
        cout << endl;
    }
}

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

這段代碼實現(xiàn)了C++中楊輝三角形的迭代方法。用戶可以輸入想要顯示的行數(shù),然后程序會打印出相應的楊輝三角形。

0