Pascal’s Triangle — Leetcode

Oshi Raghav
2 min readApr 23, 2023

Topic: Array
Difficulty: Easy
Question Number: 118

Problem Statement:
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:

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

Explanation:
Think about the image as a matrix now where each line is basically a row in the matrix. So, first things first, if you are at the edge of the matrix, the value is 1, that’s for sure. Well, any inner element is obtained by doing the sum of the 2 values present in the row just above it

  • Create an array of size (i + 1) (For some languages such as C++, you need to create a 2D array at the start of the program and resize array[i] to (i + 1)).
  • Set the first and last value of array[i] to 1.
  • Run another loop from j = 1 to i — 1 (inclusive) and for each iteration put array[i][j] = array[i — 1][j — 1] + array[i — 1][j].

Code:

in java

class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> row, pre = null;
for(int i =0; i<numRows; ++i){
row = new ArrayList<Integer>();
for(int j = 0; j<=i; ++j)
if(j==0||j==i)
row.add(1);
else
row.add(pre.get(j-1)+pre.get(j));
pre=row;
res.add(row);
}
return res;
}
}

in python by Vaishnav Jha

class Solution:
def generate(self, n: int) -> List[List[int]]:
ans = [[1]]

for i in range(n-1):
t = [0] + ans[-1] + [0] # Creating a temp list
r = [] # Creating the current row
for j in range(len(ans[-1])+1):
r.append(t[j]+t[j+1])

ans.append(r)

return ans

# Contributed By - Vaishnav Jha

Thank You
Oshi Raghav

--

--

Oshi Raghav

3rd year CSE student | GDSC Lead | Front-end developer