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;
}
};