Java Online Compiler
Example: Pascal's Triangle Space-Efficient DP in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Pascal's Triangle Space-Efficient DP 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: Iterate through each row for (int i = 0; i < numRows; i++) { // Step 2: Print leading spaces for triangular alignment for (int k = 0; k < numRows - i - 1; k++) { System.out.print(" "); } long currentVal = 1; // First element of each row is always 1 // Step 3: Iterate through each element in the current row for (int j = 0; j <= i; j++) { System.out.print(currentVal + " "); // Print the current element // Step 4: Calculate the next element using the nCr pattern: C(n,r) = C(n,r-1) * (n-r+1)/r // For Pascal's triangle, currentVal is C(i, j), nextVal is C(i, j+1) // C(i, j+1) = C(i, j) * (i - j) / (j + 1) currentVal = currentVal * (i - j) / (j + 1); } System.out.println(); // Move to the next line after each row } scanner.close(); } }
Output
Clear
ADVERTISEMENTS