LeetCode练题——118. Pascal's Triangle

1、题目

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]
]

2、我的解答

 1 # -*- coding: utf-8 -*-
 2 # @Time    : 2020/2/29 21:03
 3 # @Author  : SmartCat0929
 4 # @Email   : [email protected]
 5 # @Link    : https://github.com/SmartCat0929
 6 # @Site    : 
 7 # @File    : 118. Pascal's Triangle.py
 8 from typing import List
 9 
10 
11 class Solution:
12     def generate(self, numRows: int) -> List[List[int]]:
13         c = []
14         if numRows == 0:
15             return c
16         c.append([1])
17         if numRows == 1:
18             return c
19         for i in range(1, numRows):
20             c2 = []
21             for j in range(i + 1):
22                 if 1 <= j < i:
23                     c2.append(c[i - 1][j - 1] + c[i - 1][j])
24                 else:
25                     c2.append(1)
26             c.append(c2)
27         return c
28 
29 
30 print(Solution().generate(5))

猜你喜欢

转载自www.cnblogs.com/Smart-Cat/p/12392882.html