您的位置:首页 > 其它

Pascal's Triangle leetcode

2016-01-06 20:07 309 查看
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 = 0; i < numRows; ++i)
{
vector<int> row;
for (int j = 0; j <= i; ++j)
{
if (j == 0 || j == i)
row.push_back(1);
else
row.push_back(ret[i - 1][j - 1] + ret[i - 1][j]);
}
ret.push_back(row);
}
return ret;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: