LeetCode练题——118. Pascal's Triangle
Posted smart-cat
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 : 1027699719@qq.com 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))
以上是关于LeetCode练题——118. Pascal's Triangle的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 118 Pascal's Triangle
[Leetcode] 118. Pascal's Triangle