#include <vector>
#include <iostream>
usingnamespace std;
int pascal(int row, int col){
if(col == 0 || col == row){
return 1;
}
else{
return pascal(row-1, col-1) + pascal(row-1,col);
}
}
vector<vector<int>> generate(int numRows) {
vector<vector<int>> triangle;
for(int i = 0; i < numRows; i++){
for(int j = 0; j <= i; j++){
int v = pascal(i,j);
triangle[i].push_back(v);
}
}
return triangle;
}
int main() {
int numRows = 5;
generate(numRows);
return 0;
}
I had thought that the following code would append an element to row i of the 2D triangle vector: triangle[i].push_back(v), but this seems to be where the error lies. Any help would be much appreciated.
At line 15, triangle is initialized as an empty vector-of-vectors. It has 0 elements.
Accessing triangle[0] is undefined behavior. First, in your outer loop, do triangle.push_back(vector<int>(i+1))