Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题目解析: 帕斯卡三角,又称杨辉三角,给定一个行数,结合杨辉三角的性质,输出杨辉三角。
杨辉三角的性质为:每个数字等于上一行的左右两个数字之和。可用此性质写出整个杨辉三角。即第n+1行的第i个数等于第n行的第i-1个数和第i个数之和。
思路:利用双重for循环来打印杨辉三角,当传入的numRows不等于0时,则打印的杨辉三角一定包含数组{1},所以for循环跳过第0个数组,从1开始,声明一个用来缓存数组cur,cur用来生成第i行的数组,而第i行数组的数据个数与行数i有关,所以再次定义一个for循环,用来生成第i行数组中的数据,当j=0时,和j=i时,填充的数据都为1,而中间的数据则是等于第i-1行的j-1个数据和第j个数据之和。当内部for循环结束后,将其加入res数组中。最后返回res.
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res;
if(numRows==0)return res;
else res.push_back({1});
for(int i=1;i!=numRows;i++)
{
vector<int> cur;
//cur.push_back(1);
for(int j=0;j<=i;j++)
{
if(j==0)
{
cur.push_back(res[i-1][0]);
}
else if(j==i)cur.push_back(res[i-1][i-1]);
else cur.push_back(res[i-1][j-1]+res[i-1][j]);
}
res.push_back(cur);
}
return res;
}
};