118 楊輝三角
給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
算法
class Solution:
def generate(self, n: int,ls=[],lst=[]) -> List[List[int]]:
if n==0:return []
if n==1:return [[1]]
ls=[[1]]
while n-1:
for i in range(len(ls[-1])-1):
lst.append(ls[-1][i]+ls[-1][i+1])
lst.insert(0,1);lst.append(1)
ls.append(lst[:])
lst.clear()
n-=1
return ls
執行用時 :28 ms, 在所有 Python3 提交中擊敗了90.07%的用戶
內存消耗 :13.4 MB, 在所有 Python3 提交中擊敗了43.67%的用戶
119 楊輝三角II
給定一個非負索引 k,其中 k ≤ 33,返回楊輝三角的第 k 行。
算法
class Solution:
def getRow(self, rowIndex: int):
if rowIndex==0:return [1]
ls=[1,1]
while rowIndex-1>0:
i,tmp=0,[]
rowIndex-=1
while i<len(ls)-1:
tmp+=[ls[i]+ls[i+1]]
i+=1
ls=[1]+tmp+[1]
return ls
執行用時 :20 ms, 在所有 Python3 提交中擊敗了99.48%的用戶
內存消耗 :13.3 MB, 在所有 Python3 提交中擊敗了47.36%的用戶
class Solution:
def getRow(self, rowIndex,p=[1]):
for j in range(rowIndex):p = [1] + [p[i]+p[i+1] for i in range(len(p)-1)] +[1]
return p