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< vector<int> >result;
if (numRows<= 0)
return result;
for (int i=1; i<=numRows; i++){
vector<int> *tmp = new vector<int>();
tmp->push_back(1);
if (i == 1)
{
result.push_back(*tmp);
continue;
}
vector<int> prev = result[i-2];
for (int j=0; j<i-2; j++)
{
tmp->push_back(prev[j]+prev[j+1]);
}
tmp->push_back(1);
result.push_back(*tmp);
}
return result;
}
};