简繁EN

LeetCodeNo. 097

【LeetCode with Python】 119. Pascal's Triangle II

目錄

題目

原題頁面:https://leetcode.com/problems/pascals-triangle-ii/
題目型別:Array
難度評價:Easy
類似題目:(E) Pascal's Triangle

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?


分析

和Pascal's Triangle類似的題目,不過要求的不是輸出整個帕斯卡三角,而是輸出其中的某一層了。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
# @return a list of lists of integers
def getRow(self, rowIndex):
if rowIndex <= 0:
return [1]
elif 1 == rowIndex:
return [1, 1]
elif rowIndex >= 2:
need_rowsnum = rowIndex - 1
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)
last_row = new_row
return last_row

本文地址:https://xnerv.wang/zh-tw/leetcode-pascals-triangle-ii/