Advertisement
Spocoman

02. Pascal Triangle(matrix solution)

Oct 27th, 2024 (edited)
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Arrays;
  3.  
  4. class Main {
  5.     public static void main(String[] args) {
  6.         Scanner scanner = new Scanner(System.in);
  7.         int n = Integer.parseInt(scanner.nextLine());
  8.        
  9.         int[][] triangle = new int[n][];
  10.  
  11.         for (int row = 0; row < n; row++) {
  12.             triangle[row] = new int[row + 1];
  13.             triangle[row][0] = 1;
  14.             triangle[row][triangle[row].length - 1] = 1;
  15.  
  16.             for (int col = 1; col < row; col++) {
  17.                 triangle[row][col] = triangle[row - 1][col - 1] + triangle[row - 1][col];
  18.             }    
  19.         }
  20.  
  21.         for (int[] row : triangle) {
  22.             for (int r : row) {
  23.                 System.out.print(r + " ");
  24.             }
  25.             System.out.println();
  26.         }
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement