Pascal's Triangle (118)
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
Example:
Approach:
Pascal's triangle is essentially the embodiment of dynamic programming as we can construct each row based on the value of the previous one.
We first generate an overall Triangle list which stores all the sublist rows.
We add [1] in the triangle as it's first row and proceed to make the calculations for the subsequent rows.
We''ll have an Outer loop:
(# of rows of triangle)
as well as an Inner loop:(Taking care of row calculations).
As we're dealing with the rows in the Inner loop, (Barring element 1 and element n - 1) each element of a present row is equal to the sum of the
above element + above element + 1.
Amortized Complexity: O(N2) time
**Since Java's ArrayList allocates the required memory in chunks (typically by doubling the size when it hits the limit), we can say that ArrayList.add() has O(1) "amortized" time complexity.
Last updated
Was this helpful?