Wednesday, May 10, 2017

Pascal's Triangle



Problem Statement


Given numRows, generate the first numRows of Pascal's triangle.

Link to GitHub :Code
For example, given numRows = 5,

Return



Pascal’s Triangle
Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints first n lines of the Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.

ex of pascal triangle
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Solution

  • We need 2 arraylist . One to create arraylist and second to hold all the arraylist
  • First arraylist row is used to add initial elements of the array
          row.add(0, 1)
          Note for the first 2 iterations elements would not be altered before adding to allrows
 {1},{1,1}
  • J loop iteration would not start till Row Size is greater than one. It is responsible to altering the arrraylist elements so to generate pascal triangle
         {1},{1,1},{1,2,1}
  • The contents of the arraylist would be modified based on the size of the array.
public class PascalTriangle {
 
 public static List<List<Integer>> get(int numRows)
 {
  //List to all rows of list
  List<List<Integer>> allRows = new ArrayList<List<Integer>>();
  
  //List to store rows
  List<Integer> row = new ArrayList<Integer>();
  for(int i=0;i<numRows;i++)
  {
    //Row is used to add initial elements of the array
    //Note for the first 2 iterations elements would not be altered before adding 
    //to allrows {1},{1,1}
row.add(0, 1); for(int j=1;j<row.size()-1;j++) // set j value from the nest element row.set(j, row.get(j)+row.get(j+1)); //Add rows to the arrayList allRows.add(new ArrayList<Integer>(row)); } return allRows; }

Output
Iteration

No comments:

Post a Comment