杨辉三角

杨辉三角

描述
给一整数 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 @   hellozwx  阅读(84)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期
· 全程使用 AI 从 0 到 1 写了个小工具
· 从文本到图像:SSE 如何助力 AI 内容实时呈现?(Typescript篇)
点击右上角即可分享
微信分享提示