LeetCode 118. Pascal's Triangle

本文介绍了一种生成帕斯卡三角的算法实现。通过分析规律,使用C++编程语言,实现了从第一行到指定行数的帕斯卡三角形的生成。文中详细解释了算法的迭代过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given numRows, generate the first numRows of Pascal's triangle.

For example, given numRows = 5,
Return

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Just need to find the rule.

The first one is {1}, second one is {1, 1}. Start from 3rd one, there is a rule:

Suppose the 3rd one, we push into {1, 1, 1} which is 2ed one append one more 1. But we need to change 1 into 2. It just needs 1 + 1 --- Not clear enough? go one more then.

Suppose the 4th one, we push into {1, 2, 1, 1} which is 3rd one append one more 1. we can just make res[3][1] += res[2][0] and then res[3][2] += res[2][1]

Suppose the 5th one, we push into {1, 3, 3, 1, 1} which is 4th one append one more 1. then, change res[4][1] += res[3][0], res[4][2] += res[3][1]; res[4][3] += res[3][2]

so on and so forth....


#include <vector>
#include <iostream>
using namespace std;

vector< vector<int> > generate(int numRows) {
    if(numRows <= 0) return {};
    vector< vector<int> > res;
    res.push_back({1});
    for(int i = 2; i <= numRows; ++i) {
        vector<int> tmp = res.back();
        tmp.push_back(1);
        res.push_back(tmp);
        if(res.size() >= 3) {
            for(int j = 1; j < res[i - 1].size() - 1; ++j) {
                res[i - 1][j] += res[i-2][j - 1];
            }
        }
    }
    return res;
}

int main(void) {
    vector< vector<int> > res = generate(5);
    for(int i = 0; i < res.size(); ++i) {
        for(int j = 0; j < res[i].size(); ++j) {
            cout << res[i][j] << " ";
        }
        cout << endl;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值