Leetcode 118. Yang Hui Triangle
Question stem
Given a non-negative integer numRows, generate the first numRows rows of the Yang Hui triangle.
In the Yanghui triangle, each number is the sum of the numbers on its upper left and upper right.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
answer
Simulation, pay attention to judge the beginning and end of each line
class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int> > yhTri(numRows);
if(numRows == 0){
return yhTri;
}
yhTri[0].push_back(1);
for(int i = 1 ; i < numRows ; ++i){
for(int j = 0 ; j < i + 1 ; ++j){
yhTri[i].push_back(j == 0 || j == i ? 1 : yhTri[i-1][j-1] + yhTri[i-1][j]);
}
}
return yhTri;
}
};