题目
Given numRows, generate the first numRows of Pascal’s triangle.
For example, given numRows = 5,
Return
分析
构建数字金字塔,由上图可以清楚的找到规律。
该题目可用递归实现!
比较简单~
AC代码
class Solution {
public:
vector<vector<int>> generate(int numRows) {
if (numRows == 0)
return vector<vector<int>>();
else if (numRows == 1)
return vector<vector<int>>(1, vector<int>(1, 1));
//存储当前金字塔
vector<vector<int> > ret = generate(numRows - 1);
//计算当前行
vector<int> cur(numRows, 0);
cur[0] = 1;
cur[numRows - 1] = 1;
for (int i = 1; i < numRows - 1; ++i)
{
cur[i] = ret[numRows - 2][i - 1] + ret[numRows - 2][i];
}//for
ret.push_back(cur);
return ret;
}
};