Tag
Array
Difficulty
Easy
Description
Given an index k, return the kth row of the Pascal’s triangle.
For example, given k = 3,
Return [1,3,3,1].
Code
杨辉三角形,直观解答
class Solution(object):
def getRow1(self, rowIndex):
ans=[]
for i in range(rowIndex+1):
temp=[]
for k in range(i+1):
if k==0 or k==i:
temp.append(1)
else:
temp.append(ans[i-1][k-1]+ans[i-1][k])
ans.append(temp)
return temp
但是这样空间复杂度比较大
简化版
def getRow(self, rowIndex):
ret = [1 for i in range(rowIndex+1)]
for i in range(1,rowIndex+1):
for j in range(rowIndex-i+1,rowIndex):
ret[j]=ret[j]+ret[j+1]
return ret