LeetCode 118. Pascal's Triangle

栏目: 编程工具 · 发布时间: 7年前

内容简介:Given a non-negative integerIn Pascal’s triangle, each number is the sum of the two numbers directly above it.给定一个非负整数
  • 英文

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.

  • 中文

给定一个非负整数 numRows, 生成杨辉三角的前 numRows 行。

LeetCode 118. Pascal's Triangle

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例

输入: 5
输出:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

题解

  • 题解 1

规律:(1)第 i 层有 i 个元素。(2)每层第一个以及最后一个元素值为 1。(3)对于第 i (i > 2) 层第 j(j > 1 && j < i) 个元素 A[i][j] ,A [i][j] = A[i-1][j-1] + A[i-1][j] 。依据以上规律,使用二维数组来实现。

class Solution:
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        if numRows == 0:
            return []
        else:
            L = [[1]]
        for i in range(1, numRows):
            L1 = []
            for j in range(i+1):
                if j == 0 or j == i:	# 处理每层第一个以及最后一个元素
                    L1.append(1)
                else:	# 中间元素由+得到
                    L1.append(L[i-1][j] + L[i-1][j-1])
                    
            L.append(L1)   
        return L
  • 题解 2

思路与题解 1 一样,简化的写法。

class Solution:
    def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        res = []
        for i in range(numRows):
            res.append([1])
            for j in range(1, i + 1):
                if j == i:
                    res[i].append(1)
                else:
                    res[i].append(res[i - 1][j - 1] + res[i - 1][j])
        return res

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

与机器赛跑

与机器赛跑

[美]埃里克·布林约尔松(Erik Brynjolfsson)、[美]安德鲁·麦卡菲(Andrew McAfee) / 闾佳 / 2013-1-20 / 6.00

一场数字革命正在加速进行。 一些科幻小说里的场景已经在现实中发生:无人驾驶汽车开上了公路;智能设备能高效地翻译人类语言;人工智能系统在智力竞赛里击败了所有人类选手;工厂雇主开始购买更多的新机器,却不招新工人…… 这些例子都证明,数字技术正在快速地掌握原本只属于人类的技能,并深刻地影响了经济。虽然大多数影响是积极的:数字革新将提高效率、降低商品价格(甚至到免费),以及增加经济总量。 ......一起来看看 《与机器赛跑》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具