I'm working on a question where you are supposed return n rows of pascals triangle given and int n and return it as a List of Lists. However I'm getting an index out of bounds exception when I try to call on a previous row and I'm not exactly sure why.
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
List<Integer> row = new ArrayList<>();
for(int i = 0; i < numRows; i++){
for(int j = 0; j <= i; j++){
if(j == 0 || j == i){
row.add(1);
}
else{
if(i != 0 && j != 0){
int num = triangle.get(i-1).get(j-1) + triangle.get(i-1).get(j);
row.add(num);
}
}
}
triangle.add(row);
row.clear();
}
return triangle;
}
I added the if(i != 0 && j != 0)
line in hopes of resolving it but the error persists.