Total Accepted: 57134
Total Submissions: 188533
Difficulty: Easy
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,中间的a[i][j]=a[i-1][j-1]+a[i-1][j],所以只要填好一行后,然后压入结果就好。
class Solution {
public:vector<vector<int>> generate(int numRows)
{
vector<int> temp;
vector<vector<int>> result;
if (numRows < 1)
return{};
temp.push_back(1);
int m = 0;
result.push_back(temp);
temp.clear();
for (int i = 2; i <= numRows; i++)
{
temp.push_back(1);
for (int j = 2; j < i; j++)
{
m = result[i - 2][j - 2] + result[i - 2][j-1];
temp.push_back(m);
}
temp.push_back(1);
result.push_back(temp);
temp.clear();
}
return result;
}
};