您的位置:首页 > 其它

118. Pascal's Triangle 杨辉三角

2017-05-02 16:53 309 查看
118. Pascal's Triangle

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

按照规律写两个循环即可,但是要注意新值覆盖旧值的问题,而且只能计算一半,剩下一半对称复制。
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<int> happy;
vector<vector<int>> res;
if(numRows==0) return res;
happy.push_back(1);
res.push_back(happy);
if(numRows==1) return res;
happy.push_back(1);
res.push_back(happy);
if(numRows==2) return res;
for(int i=3;i<=numRows;i++)
{
for(int j=(happy.size())/2;j>=1;j--)//这个循环要从大到小
{
happy[j]=happy[j]+happy[j-1];
happy[happy.size()-j]=happy[j];
}
happy.push_back(1);
res.push_back(happy);
}
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 数组