leetcode 118. Pascal's Triangle(python3)楊輝三角
阿新 • • 發佈:2019-01-04
題目:楊輝三角
題目分析:
楊輝三角,第一個第二組數的值由第一組數的值決定,例如,x[2][1]=x[1][0]+x[1][1] 既:2=1+1
程式設計思路:
1.題目給出輸入為一個numRows變數,控制楊輝三角行數,輸出 List[list[int]]型別
2.考慮楊輝三角 x[2][1]=x[1][0]+x[1][1] 的特性,通過兩個list實現,x[ ]一個用於計算,w[ ] 用於輸出
程式程式碼:
class Solution: def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ #定義x,w x = [] w = [] #通過for迴圈,建立全1 list x for i in range(numRows): x.append([]) for j in range(numRows): x[i].append(1) #楊輝三角核心公式 for i in range(2, numRows): for j in range(1, i): x[i][j] = x[i - 1][j - 1] + x[i - 1][j] #通過for 迴圈輸出楊輝三角 for i in range(numRows): w.append([]) # print x for j in range(i+1): w[i].append(x[i][j]) return w