約 1 分鐘49 字123 個單字
題目
原題頁面:https://leetcode.com/problems/pascals-triangle/
題目型別:Array
難度評價:Easy
類似題目:(E) Pascal's Triangle II
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
分析
輸出帕斯卡三角,明白帕斯卡三角的定義即可簡單解題。
程式碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution: def generate(self, numRows): rows = [] if numRows <= 0: return rows if numRows >= 1: rows.append([1]) if numRows >= 2: rows.append([1, 1]) if numRows >= 3: need_rowsnum = numRows - 2 last_row = [1, 1] for i in range(0, need_rowsnum): new_row = [1] for j in range(1, len(last_row)): new_row.append(last_row[j - 1] + last_row[j]) new_row.append(1) rows.append(new_row) last_row = new_row return rows
|
本文地址:https://xnerv.wang/zh-tw/leetcode-pascals-triangle/