美文网首页
[LeetCode] Pascal's Triangle

[LeetCode] Pascal's Triangle

作者: lalulalula | 来源:发表于2017-11-22 19:54 被阅读0次

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

2.题目要求:思路基础题,杨辉三角。

3.方法:顺序加入每一个vector就好,其中注意元素的个数与求和关系。

4.代码:
class Solution {
public:
vector<vector<int> > generate(int numRows) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int>> ans;
for(int i = 0;i < numRows;i++)
{
vector<int> cur;
if(i == 0)
cur.push_back(1);
else
{
for(int j = 0;j <= i;j++)
{
if(j == 0 || j == i) cur.push_back(1);
else cur.push_back(ans[i - 1][j] + ans[i - 1][j - 1]);
}
}
ans.push_back(cur);
}

    return ans;
}

};

相关文章

网友评论

      本文标题:[LeetCode] Pascal's Triangle

      本文链接:https://www.haomeiwen.com/subject/tbvovxtx.html