Pascal's Triangle — LeetCode 118 Python Solution
- Problem
- #118
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer numRows, return the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
This statement is abridged. Read the full problem on LeetCode.
Example
- Input
- numRows = 5
- Output
- [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Python solution
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
f = [[1]]
for i in range(numRows - 1):
g = [1] + [a + b for a, b in pairwise(f[-1])] + [1]
f.append(g)
return fComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the given number of rows |
| Space | O(1) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 118. Pascal's Triangle is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 118. Pascal's Triangle?
- LeetCode 118. Pascal's Triangle is rated Easy on LeetCode.
- What is the time complexity of LeetCode 118. Pascal's Triangle?
- The Python solution on this page runs in O(n^2), where n is the given number of rows.
- What is the space complexity of LeetCode 118. Pascal's Triangle?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 118. Pascal's Triangle cover?
- LeetCode 118. Pascal's Triangle is tagged Array and Dynamic Programming on LeetCode.