Algorithm/LeetCode
[LeetCode] [DP] 118. Pascal's Triangle
Eric_Park
2021. 10. 25. 13:09
118. Pascal's Triangle
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]]
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows == 1:
return [[1]]
if numRows == 2:
return [[1], [1,1]]
blank =[]
for zeros in range(numRows):
blank.append( [ 0 for i in range(zeros+1) ] )
for i in range(numRows):
blank[i][0] = 1
blank[i][-1] = 1
for i in range(2, numRows):
for k in range(1,i):
blank[i][k] = blank[i-1][k-1] + blank[i-1][k]
return blank
@credit to sherlock321
def generate(self, numRows):
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x+y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]
explanation: Any row can be constructed using the offset sum of the previous row. Example:
1 3 3 1 0
+ 0 1 3 3 1
= 1 4 6 4 1