給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。在楊輝三角中,每個數是它左上方和右上方的數的和。
示例:
輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
沒有什麼特別的,背住套路,其實就是讓你熟悉數組之間的index的邏輯關係吧,純數據結構,不涉及算法,這種其實是最空洞枯燥的,就跟背九九乘法表差不多的意義。
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
triangle = []
for row_num in range(numRows):
# The first and last row elements are always 1.
row = [1]*(row_num+1)
# Each triangle element is equal to the sum of the elements
# above-and-to-the-left and above-and-to-the-right.
for j in range(1, row_num):
row[j] = triangle[row_num-1][j-1] + triangle[row_num-1][j]
triangle.append(row)
return triangle