Pascal's triangle and 2D vector

I'm trying to solve the following problem given here: https://leetcode.com/problems/pascals-triangle/description/

However, when I try and fill the 2D vector called triangle, I seem to be getting an error that I cannot fix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <vector>
#include <iostream>
using namespace 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.
Last edited on
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))
Last edited on
one of those weird math tricks: you can seed it with pow(11,0) through pow(11,4) to get the first 5 rows of the triangle.


Topic archived. No new replies allowed.