From 2bd2f19d27bd42c47122caf405ce785c4c34a7b7 Mon Sep 17 00:00:00 2001 From: "Amisha.Sahu" <115696152+Amisha2093@users.noreply.github.com> Date: Thu, 20 Oct 2022 17:25:09 +0530 Subject: [PATCH] Pascal's Triangle code added in Java --- PascalsTriangle.java | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 PascalsTriangle.java diff --git a/PascalsTriangle.java b/PascalsTriangle.java new file mode 100644 index 0000000..802e03c --- /dev/null +++ b/PascalsTriangle.java @@ -0,0 +1,39 @@ +// Pascal's Triangle +// Problem Description: +/* +Given an integer numRows, return the first numRows of Pascal's triangle. +In Pascal's triangle, each number is the sum of the two numbers directly above it +*/ + +// Implementation: +class Solution { + public List> generate(int numRows) { + // Create an array list to store the output result... + List> output = new ArrayList>(); + // Base cases... + if (numRows <= 0) return output; + // Create an array list to store the prev triangle value for further addition... + ArrayList prev = new ArrayList(); + // Inserting for the first row & store the prev array to the output array... + prev.add(1); + output.add(prev); + // For rest of the rows, Traverse all elements through a for loop... + for (int i = 2; i <= numRows; i++) { + // Create another array to store the current triangle value... + ArrayList curr = new ArrayList(); + curr.add(1); //first + // Calculate for each of the next values... + for (int j = 0; j < prev.size() - 1; j++) { + // Inserting the addition of the prev arry two values... + curr.add(prev.get(j) + prev.get(j + 1)); //middle + } + // Store the number 1... + curr.add(1); //last + // Store the value in the Output array... + output.add(curr); + // Set prev is equal to curr... + prev = curr; + } + return output; // Return the output list of pascal values... + } +}