Tuesday, June 3, 2014

Leetcode (Python): Pascal's Triangle

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

Solution:

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

1 comment :