Pascal's Triangle II — LeetCode 119 Python Solution
- Problem
- #119
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an integer rowIndex, return the rowIndexth (0-indexed) row of the 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
- rowIndex = 3
- Output
- [1,3,3,1]
Python solution
class Solution:
def getRow(self, rowIndex: int) -> List[int]:
f = [1] * (rowIndex + 1)
for i in range(2, rowIndex + 1):
for j in range(i - 1, 0, -1):
f[j] += f[j - 1]
return fComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 119. Pascal's Triangle II 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 119. Pascal's Triangle II?
- LeetCode 119. Pascal's Triangle II is rated Easy on LeetCode.
- What is the time complexity of LeetCode 119. Pascal's Triangle II?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 119. Pascal's Triangle II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 119. Pascal's Triangle II cover?
- LeetCode 119. Pascal's Triangle II is tagged Array and Dynamic Programming on LeetCode.