LeetCode 0118. Pascal's Triangle Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0118. Pascal's Triangle

Description

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:

 

Example 1:

Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2:

Input: numRows = 1
Output: [[1]]

 

Constraints:

  • 1 <= numRows <= 30

Solutions

Solution 1: Simulation

We first create an answer array f, then set the first row of f to [1]. Next, starting from the second row, the first and last elements of each row are 1, and for other elements f[i][j] = f[i - 1][j - 1] + f[i - 1][j].

The time complexity is O(n^2), where n is the given number of rows. Ignoring the space consumption of the answer, the space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptC#
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 f(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !