118. 杨辉三角
题目介绍
给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
示例 2:
输入: numRows = 1
输出: [[1]]
提示:
1 <= numRows <= 30
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/pascals-triangle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> res_all;
res_all.push_back({1});
if(numRows == 1) return res_all;
res_all.push_back({1,1});
if(numRows == 2) return res_all;
for(int i=2; i<numRows; i++){
vector<int> res(i+1, 1);
int now = 1;
for(int j=1; j<i; j++){
res[j] = now;
now = res_all[i-1][j];
res[j] += now;
}
res_all.push_back(res);
}
return res_all;
}
};