Thursday, 29 July 2021

Pascal's Triangle - LeetCode 118

 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 as shown:

 

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

Solution: 

Note: Only function is written


class Solution {

    public List<List<Integer>> generate(int numRows) {

        

        List<List<Integer>> triangle = new ArrayList<>(); //created empty List of lists

        

        if(numRows==0)

            return triangle;

        

        

        List<Integer> first_row = new ArrayList<>(); //created first row 

        first_row.add(1); // and assigned 1 to first row

        

        triangle.add(first_row); //adding first row to our List of lists

        

        

        //Looping through each row

        for(int i=1;i<numRows;i++){

            List<Integer> prev_row=triangle.get(i-1); //retreiving previous row from triangle

            List<Integer> row = new ArrayList<>(); // creating an empty row to fill each element in this row

            

            row.add(1); // adding 1 at first as 1 is the first element for every row

            

            for(int j=1;j<i;j++){

                row.add(prev_row.get(j-1)+prev_row.get(j)); // summing up elements in previous row and filling in the row   

                

            }

            

            row.add(1); // adding 1 to row as last element for every row is 1

            triangle.add(row); // Now adding the row to List of lists

            

        }

        

        return triangle;

        

    }

}

Output:

Your input
5
Output
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Expected
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

1 comment:

  1. I found that solution is very popular and helpful: https://youtu.be/XhppEP4OPHQ

    ReplyDelete

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...