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_118 {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> vecs;
vector<int> vec;
if (numRows==0)
{
return vecs;
}
//if (numRows==1) //放在循环中
//{
// vec.push_back(1);
// vecs.push_back(vec);
// return vecs;
//}
//if (numRows == 2)
//{
// vec.push_back(1);
// vecs.push_back(vec);
// vec.clear();
// vec.push_back(1);
// vec.push_back(1);
// vecs.push_back(vec);
//
// return vecs;
//}
//vec.push_back(1);
//vecs.push_back(vec);
//vec.clear();
//vec.push_back(1);
//vec.push_back(1);
//vecs.push_back(vec);
//vec.clear();
for (int i = 1; i <= numRows;i++)
{
vec.resize(i,1); //vector<int> tmp(i,1);
for (int j = 1; j < vec.size()-1; j++)
{
vec[j] = vecs[i - 2][j - 1] + vecs[i - 2][j];
}
vecs.push_back(vec);
}
return vecs;
}
};
题目来源