# 用时0ms
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
# 第 n 行要用到 n-1 行的数据,应该是个动态规划吧
# n = [1 n-1[0]+n-1[1] .... n-1[n-2]+n-1[n-1]]
if numRows == 0:
return []
if numRows == 1:
return [[1]]
if numRows == 2:
return [[1], [1, 1]]
list1 = [[1], [1, 1]]
for i in range(3, numRows + 1):
list1.append(self.help(list1))
return list1
# 已知第n行 求n+1行
def help(self, list1):
new = []
for j in range(len(list1[-1]) - 1):
new.append(list1[-1][j] + list1[-1][j + 1])
new = [1] + new + [1]
return new
# leetcode 最优解 0ms
class Solution2(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
if numRows == 1:
return [[1]]
res = [[1]]
def recursion(row):
if row == numRows:
return
res.append([])
# 在开头添加一个1
res[row].append(1)
for i in range(row-1):
tmp = res[row-1][i]+res[row-1][i+1]
res[row].append(tmp)
# 在最后添加一个1
res[row].append(1)
recursion(row+1)
recursion(1)
return res
s = Solution()
print(s.generate(5))
网友评论