118. Pascal's Triangle
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]
]
我原创的思路:和跑的最快的python解法相同
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res=[[1],[1,1]]
if numRows<3:
return res[:numRows]
CurrentExistMaxRowNum=2
while(CurrentExistMaxRowNum<numRows):
currentRowContent=[1]
for i in range(0,len(res[CurrentExistMaxRowNum-1])-1):
currentRowContent.append(res[CurrentExistMaxRowNum-1][i]+res[CurrentExistMaxRowNum-1][i+1])
currentRowContent.append(1)
res.append(currentRowContent)
CurrentExistMaxRowNum=CurrentExistMaxRowNum+1
return res
119. Pascal's Triangle II
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?
我的解法:在118的基础上直接改的,注意本题的参数rowIndex,是数组意义上的,第一行的rowIndex为0;而118题中的numRows则是非数组意义的,第一行的numRows为1。所以我就直接numRows=rowIndex+1,然后再改一改返回值就AC了。但是不符合题目要求的O(k)空间
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
numRows=rowIndex+1
res=[[1],[1,1]]
if numRows==0:
return []
if 0<numRows<3:
return res[:numRows][rowIndex]
CurrentExistMaxRowNum=2
while(CurrentExistMaxRowNum<numRows):
currentRowContent=[1]
for i in range(0,len(res[CurrentExistMaxRowNum-1])-1):
currentRowContent.append(res[CurrentExistMaxRowNum-1][i]+res[CurrentExistMaxRowNum-1][i+1])
currentRowContent.append(1)
res.append(currentRowContent)
CurrentExistMaxRowNum=CurrentExistMaxRowNum+1
return res[rowIndex]
看了一下最快的python答案(26ms)的解法,厉害厉害!如下:
class Solution(object):
def getRow(self, rowIndex):
"""
:type rowIndex: int
:rtype: List[int]
"""
if rowIndex is None or rowIndex<0:
return []
if rowIndex==0:
return [1]
curr=[1,1]
for i in range(2,rowIndex+1):
for j in range(i-1):
curr[j]=curr[j]+curr[j+1]
curr=[1]+curr
return curr
我走了一遍人家的流程才想明白:
它确实用O(k)的空间,就是curr这个变量
比如rowIndex=4,举其中的一步就容易明白了:
它从curr=[1,3,3,1]变成curr=[1,4,6,4,1]是这样的:
模拟:
当前的curr=[1,3,3,1]
i=4,j=0时, curr[0]=curr[0]+curr[1]=1+3=4,curr=[4,3,3,1]
i=4,j=0时, curr[1]=curr[1]+curr[2]=3+3=6,curr=[4,6,3,1]
i=4,j=0时, curr[2]=curr[2]+curr[3]=3+1=4,curr=[4,6,4,1]
最后再由这句变成
curr=[1]+curr
curr=[1,4,6,4,1]
确实精辟!curr的空间可以循环利用,比我原来写的先生成全部的Psacal Triangle再返回特定行要好多了!