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] ]
题目解析:
方案一:
一行一行生成,每一行首先要放入一个元素1,然后后面的元素是上一层的两个元素的和,最后也要放入一个1。
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<int> tmp;
if(numRows == 0)
return res;
tmp.push_back(1);
res.push_back(tmp);
while(numRows > 1){
numRows--;
tmp = GenerateSub(tmp);
res.push_back(tmp);
}
return res;
}
vector<int> GenerateSub(vector<int> arr){
vector<int> tmp;
tmp.push_back(1);
int n = arr.size();
for(int i = 0;i < n-1;i++){
tmp.push_back(arr[i]+arr[i+1]);
}
tmp.push_back(1);
return tmp;
}
private:
vector<vector<int> > res;
};
方案二:
容器的容器,可以看成一个二维数组,当然不是完整的,每一行的元素个数不一样。但能像二维数组一样去引用每一个元素。
class Solution {
public:
vector<vector<int> > generate(int numRows) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int>> ans;
for(int i = 0;i < numRows;i++)
{
vector<int> cur;
if(i == 0)
cur.push_back(1);
else
{
for(int j = 0;j <= i;j++)
{
if(j == 0 || j == i) cur.push_back(1);
else cur.push_back(ans[i - 1][j] + ans[i - 1][j - 1]);
}
}
ans.push_back(cur);
}
return ans;
}
};