[LeetCode] Pascal's Triangle

118. Pascal’s Triangle

Given an integer numRows, return the first numRows of Pascal’s triangle.

In Pascal’s triangle, each number is the sum of the two numbers directly above it as shown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
vector<vector<int>> generate(int numRows) {
if(numRows == 1) return {{1}};
vector<vector<int>> res = {{1},{1,1}};
numRows -= 2;
while(numRows--) {
vector<int> row;
row.push_back(1);
for(int i = 0; i < res.back().size() - 1; i++) {
row.push_back(res.back()[i] + res.back()[i+1]);
}
row.push_back(1);
res.push_back(row);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/12/PS/LeetCode/pascals-triangle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.