Java Online Compiler
Example: Pascal's Triangle Generator in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle Generator import java.util.ArrayList; import java.util.List; // Main class containing the entry point of the program public class Main { // LeetCode-style solution method public static List<List<Integer>> generate(int numRows) { List<List<Integer>> triangle = new ArrayList<>(); if (numRows == 0) { return triangle; } // The first row is always [1] List<Integer> firstRow = new ArrayList<>(); firstRow.add(1); triangle.add(firstRow); // Iterate from the second row up to numRows for (int i = 1; i < numRows; i++) { List<Integer> prevRow = triangle.get(i - 1); // Get the previous row List<Integer> currentRow = new ArrayList<>(); // The first element of every row is always 1 currentRow.add(1); // Calculate inner elements based on the previous row for (int j = 1; j < i; j++) { // Each element is the sum of the two elements directly above it currentRow.add(prevRow.get(j - 1) + prevRow.get(j)); } // The last element of every row is always 1 currentRow.add(1); // Add the newly formed row to the triangle triangle.add(currentRow); } return triangle; } public static void main(String[] args) { // Test cases System.out.println("Pascal's Triangle for numRows = 1:"); System.out.println(generate(1)); // Expected: [[1]] System.out.println("\nPascal's Triangle for numRows = 3:"); System.out.println(generate(3)); // Expected: [[1], [1, 1], [1, 2, 1]] System.out.println("\nPascal's Triangle for numRows = 5:"); System.out.println(generate(5)); /* Expected: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] */ } }
Output
Clear
ADVERTISEMENTS