-
[LeetCode] [DP] 118. Pascal's TriangleAlgorithm/LeetCode 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
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode] [DP] 746. Min Cost Climbing Stairs (0) 2021.10.08 [LeetCode] [DP] 53. Maximum Subarray (0) 2021.10.05 [LeetCode]229. Majority Element II (0) 2021.09.29 [LeetCode] 169. Majority Element (0) 2021.09.29 [LeetCode]567. Permutation in String (0) 2021.09.26