leetcode 118. Pascal's Triangle 详解 python3

一.问题描述

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

二.解题思路

解决这道题,主要是确定每一个值是怎么赋值的。

每一个值是被它上一行与其相邻的两个元素的和。

怎样判断相邻?可知下一行比上一行左右各多出一个元素,这个元素是1,这俩元素很容易确定,不用讨论它的更新。

因此上一行与当前行相邻的元素的索引:假设当前待更新值索引为t,那么上一行与其相邻的索引为t-1和t。

所以更新公式就是

res[i][t]=res[i-1][t-1]+res[i-1][t]

主要就是注意一下边界处理,不过这对python很友好,因为python array[-1]=array[n-1],n为数组长度。

更多leetcode算法题解法: 专栏 leetcode算法从零到结束

三.源码

给出两种。

1.这种实现仅限于python,因为python的列表索引机制,负的索引相当于从后往前索引.

代码相当简洁,没有专门去处理n为1的情况。第二个循环里的(1,len(res[i]-1)能很好的初始n=1和n=2时的情况。

注意一下两个版本第二个循环的范围,第一个是根据当前i来索引,生成当前行,第二个是根据前一个i-1来索引生成当前行,因为第一个版本一开始就把当前n的列表给初始好了,而第二个没有。

更新: 来一个实现更简洁的,很好的利用了每一行元素的个数就是当前行索引值+1

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if not numRows:return []
        res=[0]*numRows
        for i in range(numRows):
            res[i]=[0]*(i+1)
            res[i][0],res[i][-1]=1,1
            for t in range(1,len(res[i])-1):
                res[i][t]=res[i-1][t-1]+res[i-1][t]
        return res

2.其他实现语言的参考

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        if not numRows:return []
        if numRows==1:return [[1]]
        res=[[1],[1,1]]
        for i in range(2,numRows):
            res.append([1])
            for t in range(len(res[i-1])-1):
                res[i].append(res[i-1][t]+res[i-1][t+1])
            res[i].append(1)
        return res

3.来源:leetcode demo

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        
        triangle = [[1]*(i+1) for i in range(numRows)]
        
        
        for i in range(numRows):
            
            for j in range(1, i):
                
                triangle[i][j] = triangle[i-1][j] + triangle[i-1][j-1]
                
        return triangle
发布了218 篇原创文章 · 获赞 191 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/CSerwangjun/article/details/103210105