Given an integer
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown in below diagram:
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Output: [[1]]
Contents
Solution using previous row values
In this approach, we are simply going to use previous row values and compute the values for current row.
-
We will create a function
usingPreviousRowValues that takes input argumentnumRows . -
We are then going to create create a variable
result of typeList<List<Integer>> , that is our return type.List<List<Integer>> result = new ArrayList<>(); -
In the first step, we are going to create the first row elements, that is
[1] and add it to theresult list. If thenumRows is 1, then we simply returnresult at this step. -
Next, we will also add second row elements, that is
[1, 1] and add it to theresult . -
Then, loop through from 3rd row (i.e. 2nd index) until
numRows , add element '1' on both ends of the row, then from index 1 untilcurrentRow add previous row's elements at indexi-1 andi as shown below.currentRow.add(previousRow.get(j-1) + previousRow.get(j));
Complexity Analysis:
Time complexity: Above code runs in O(n2) time where
Space complexity: O(n2) for the
Above implementations source code can be found at