118. Pascal's Triangle Leetcode Python

来源:互联网 发布:大数据专业课程 编辑:程序博客网 时间:2024/05/26 08:42
Given numRows, generate the first numRows of Pascal's triangle.


For example, given numRows = 5,
Return


[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]

]

这道题是构造pascal 三角形主要是要建立一个prerow 一个currow 然后每次下一行的除了开始以及结束的位置,中间位置currow.append(prerow[pos]+prerow[pos+1])最后再在最后补一个1

we need to define a prerow and currow  everytime we add 1 to currow first and close it with 1, beside that currow.append(prerow[pos]+prerow[pos+1])


the code is as follow:

class Solution:    # @return a list of lists of integers    def generate(self, numRows):        solution=[]        if numRows==0:            return solution        if numRows>0:            actualrow=[1]            solution.append(actualrow)            for index in range(1,numRows):                prerow=actualrow                actualrow=[1]                for j in range(0,index-1):                    actualrow.append(prerow[j]+prerow[j+1])                actualrow.append(1)                solution.append(actualrow)        return solution


0 0
原创粉丝点击