118. Pascal's Triangle
难度: 简单
刷题内容
原题连接
- https://leetcode.com/problems/pascals-triangle
内容描述
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
解题方案
思路 1
高中数学知识,把行数理理清楚就ok
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows == 0:
return []
res = [[1]]
for i in range(1, numRows):
tmp = [1]
for j in range(1, i):
tmp.append(res[-1][j-1]+res[-1][j])
tmp.append(1)
res.append(tmp)
return res
或者可以写得更简单一些,这里谢谢荼靡大佬的想法,棒!
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res = [[1]]
for i in range(1, numRows):
res.append(map(lambda x,y:x+y, [0]+res[-1], res[-1]+[0]))
return res[:numRows]