Java Online Compiler
Example: Pascal's Triangle using Dynamic Programming in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle using Dynamic Programming import java.util.ArrayList; import java.util.List; import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter the number of rows for Pascal's Triangle: "); int numRows = scanner.nextInt(); // Step 1: Initialize a list to store all rows of the triangle List<List<Integer>> triangle = new ArrayList<>(); // Step 2: Iterate to generate each row for (int i = 0; i < numRows; i++) { // Step 3: Create a new list for the current row List<Integer> currentRow = new ArrayList<>(); // Step 4: Iterate to generate elements of the current row for (int j = 0; j <= i; j++) { if (j == 0 || j == i) { // First and last elements of each row are always 1 currentRow.add(1); } else { // Sum the two elements from the previous row List<Integer> prevRow = triangle.get(i - 1); int sum = prevRow.get(j - 1) + prevRow.get(j); currentRow.add(sum); } } // Step 5: Add the completed current row to the triangle triangle.add(currentRow); } // Step 6: Print the generated triangle for (int i = 0; i < numRows; i++) { // Print leading spaces for alignment for (int k = 0; k < numRows - i - 1; k++) { System.out.print(" "); } for (int num : triangle.get(i)) { System.out.print(num + " "); } System.out.println(); } scanner.close(); } }
Output
Clear
ADVERTISEMENTS