Pascal's Triangle – Solution & Complexity
1. Understand the Pattern
- Row
0is[1]. - Every later row begins and ends with
1. - An interior value at position
jequals the sum of positionsj-1andjin the previous row.
2. Build Row by Row
- Start the result with the first row
[1]. - For each new row, walk the previous row and add adjacent pairs.
- Wrap the sums with a leading and trailing
1.
3. Rolling Previous Row
- You never need more than the previous row to build the next one.
- Derive the next row by zipping the previous row shifted by one.
- This keeps the logic to pure additions.
4. Final Solution and Complexity
- Each of the
numRowsrows costs work proportional to its length. - Total time is
O(numRows^2). - Space is
O(numRows^2)for the returned triangle.