Pascal's Triangle leetcode

时间:2023-03-09 07:26:03
Pascal's Triangle leetcode

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]
]

Subscribe to see which companies asked this question

0 0
0[1]0
0[1 1]0
0[1 2 1]0
0[1 3 3 1]0
0[1 4 6 4 1]

帕斯卡三角形,它的值 a[i][j] = a[i-1][j-1] + a[i-1][j]; 注意如果i-1<0,则a[i-1]=0,也就是假设三角形周边的元素都是0

程序中我们可以直接让边缘的数值为1

vector<vector<int>> generate(int numRows) {
vector<vector<int>> ret;
for (int i = ; i < numRows; ++i)
{
vector<int> row;
for (int j = ; j <= i; ++j)
{
if (j == || j == i)
row.push_back();
else
row.push_back(ret[i - ][j - ] + ret[i - ][j]);
}
ret.push_back(row);
}
return ret;
}