Pascal’s Triangle
1. Pascal’s Triangle
Difficulty: Easy
Related Topics: Array, Dynamic Programming
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]]
Code:
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
pascal = [[] for i in range(numRows)]
for index in range(len(pascal)):
if index == 0:
pascal[index] = [1]
elif index == 1:
pascal[index] = [1,1]
else:
for i in range(len(pascal[index-1])):
if i != len(pascal[index-1])-1:
pascal[index].append(pascal[index-1][i]+pascal[index-1][i+1])
pascal[index].append(1)
pascal[index].insert(0,1)
return pascal
Feedbacks:
I first set the base case when there are one and two rows. And then I used dynamic programming algorithms to calculate the elements of rows which is over 2. It passed the problem, but I think I can make the code more simpler.