Skip to content

Instantly share code, notes, and snippets.

@tewari2312
Created May 5, 2024 12:19
Show Gist options
  • Select an option

  • Save tewari2312/0f80ba65d9c7580de2f63218a9a87bd7 to your computer and use it in GitHub Desktop.

Select an option

Save tewari2312/0f80ba65d9c7580de2f63218a9a87bd7 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.List;
class PascalTriangle {
public static void main(String[] args) {
System.out.println(new PascalTriangle().generate(7));
}
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
list1.add(1);
List<Integer> list2 = new ArrayList<>();
list2.add(1);
list2.add(1);
List<Integer> list3 = new ArrayList<>();
list3.add(1);
list3.add(2);
list3.add(1);
list.add(list1);
if(numRows==1)
return list;
list.add(list2);
if(numRows==2)
return list;
list.add(list3);
if(numRows==3)
return list;
if(numRows>3){
int index = 2;
while(index<numRows-1){
List<Integer> indexList = new ArrayList<>();
indexList.add(1);
List<Integer> previousList = list.get(index);
for (int i = 1; i < previousList.size(); i++)
indexList.add(previousList.get(i)+previousList.get(i-1));
indexList.add(1);
list.add(indexList);
index++;
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment