118. Pascal's Triangle
https://leetcode.com/problems/pascals-triangle/
Last updated
Was this helpful?
https://leetcode.com/problems/pascals-triangle/
Last updated
Was this helpful?
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
1. Input is 0 (asking for 0 rows of Pascal)
Given the output format is asking us to return an array, for 0 we can return an empty array
return []
2. Input is 1 (asking for 1 row of Pascal)
This depends on how I create the list of Pascal, but I plan to create an iterative solution using the second row, therefore I create a separate case for this input. So when the input is 1, I will return the first row exclusively in a list
return [[1]]
So if n
doesn't fall into any of the above edge cases, we can start with the second row, and iterate until our solution is the length of n. So to generate Pascal's Triangle iteratively, we simply take the previous row and use it to generate the next row.
Therefore, if we start using the second row, we begin with [[1],[1,1]]
.
We can then generate elements of the new row by summing neighbouring elements of the previous row and appending to create a new row.
So this iterative generation happens until the length of our triangle array is actually the same as the input, n. So coming together, the solution looks like this: