[勇者闯LeetCode] 118. Pascal’s Triangle
Description
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]
]
Information
- Tags: Array
- Difficulty: Easy
Solution
找规律:
1.
new[0]=old[0]
,
2.
new[i]=old[i]+old[i−1]
,when
0<i<len(old)
,
3.
new[len(old)]=1
。
Python Code
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if numRows <= 0:
return []
result = [[1]]
for _ in range(numRows-1):
temp = result[-1][:]
for i in range(len(temp)-1, 0, -1):
temp[i] += temp[i-1]
temp += [1]
result.append(temp)
return result