杨辉三角

杨辉三角

描述
给一整数 n, 返回杨辉三角的前 n 行

0 <= n <= 20
杨辉三角也被叫做帕斯卡三角形. --(Wikipedia)

【样例】

输入 : n = 4
输出 :
[
 [1]
 [1,1]
 [1,2,1]
 [1,3,3,1]
]

【方法一】

#include <iostream>
#include <cstdio>


using namespace std;


const int MAXN = 20 + 10;
int num[MAXN][MAXN];


int main() {

    int n = 4;

    printf("请输入 n 的值:");

    while (scanf("%d", &n) != EOF) {

        printf("\n");

        for (int row = 0; row < n; row++) {
            for (int col = 0; col <= row; col++) {
                if (col == 0 || col == row) {
                    num[row][col] = 1;
                }else {
                    num[row][col] = num[row - 1][col - 1] + num[row - 1][col];
                }
                printf("%3d", num[row][col]);
            }
            printf("\n");
        }

        printf("\n");

        printf("请输入 n 的值:");

    }

    return 0;
}

【方法二】

#include <iostream>
#include <cstdio>
#include <vector>


using namespace std;


int main() {
    
    int n = 5;
    
    cout << "请输入 n 的值:";
    
    while (scanf("%d", &n) |= EOF) {
        
        vector<vector<int>> answer(n, vector<int>());
        
        cout << endl;
        
        for (int row = 0; row < n; row++) {
            // 每行 最左端 和 最右端 元素都为 1
            // resize: 改变当前 vector 的元素数量为 row + 1,并对新建的元素赋值为 1.
            answer[row].resize(row + 1, 1);
            // 每行中间位置上的数 == 上一行 (当前元素向左一列的数 + 当前元素当前列的数)
            for (int col = 0; col < row; col++) {
                answer[row][col] = answer[row - 1][col - 1] + answer[row - 1][col];
            }
        }
        
        for (int row = 0; row < n; row++) {
            for (int col = 0; col <= row; col++) {
                cout << answer[row][col] << " ";
            }
            cout << endl;
        }       
        
        cout << endl;
        
        cout << "请输入 n 的值:";
    }
    
    return 0;
    
}

【结果】

请输入 n 的值:5

  1
  1  1
  1  2  1
  1  3  3  1
  1  4  6  4  1

请输入 n 的值:4

  1
  1  1
  1  2  1
  1  3  3  1

请输入 n 的值:3

  1
  1  1
  1  2  1

请输入 n 的值:
posted @ 2022-02-12 19:07  hellozwx  阅读(19)  评论(0编辑  收藏  举报