- Pascal's Triangle Easy
1459
110
Add to List
Share 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] ]
思路:杨辉三角,两次遍历
代码:python3
class Solution:
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
listA = [];
for i in range(numRows):
listA.append([1]*(i+1));
if i>1 :
for j in range(1,i):
listA[i][j]=listA[i-1][j-1]+listA[i-1][j];
return listA;
if __name__=='__main__':
print(Solution().generate(20));
空间复杂度:O(numRows^2) 时间复杂度:O(numRows^2)