problem:
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] ]Array
题意:帕斯卡三角形,又名杨辉三角形,是多项式(a+b)^n的系数
thinking:
(1)杨辉三角形,从第三行开始,排除第一个和最后一个1外,其值是上一行上面的两个元素值之和。参考:维基百科-杨辉三角形
(2)从第三行开始,每一行的元素由上一行的元素决定
code:
class Solution {
private:
vector<vector<int> > ret;
public:
vector<vector<int> > generate(int numRows) {
vector<int> row1(1,1);
vector<int> row2(2,1);
ret.clear();
if(numRows==0)
return ret;
if(numRows==1)
{
ret.push_back(row1);
return ret;
}
if(numRows==2)
{
ret.push_back(row1);
ret.push_back(row2);
return ret;
}
ret.push_back(row1);
ret.push_back(row2);
for(int i=3;i<=numRows;i++)
{
vector<int> tmp;
vector<int> pre=ret[i-2];
tmp.push_back(1);
for(int j=0;j<pre.size()-1;j++)
tmp.push_back(pre[j]+pre[j+1]);
tmp.push_back(1);
ret.push_back(tmp);
}
return ret;
}
};