Pascal Triangle

def generate(self, numRows):
        """
        :type numRows: int
        :rtype: List[List[int]]
        """
        answer = []
        
        if numRows == 0:
            return []
            
        row = [1]
        answer.append(row)
        
        for x in range(2, numRows+1):
            # Prepare the row
            row = [1]*x
            # The first and last element on each row is 1, so skip those
            # indexes.
            for y in range(1, x-1):
                # print("x={} y={} answer={}".format(x, y, answer))
                
                # x represent row number. We need to normalize it
                # to use it as an index in the answer list.
                previousRow = answer[x-2]
                
                # In the previous row, pick an element before the current index
                # and another at the current index; sum them. 
                row[y] = previousRow[y-1]+ previousRow[y]
                
            answer.append(row)
                
        return answer

Output

x=3 y=1 answer=[[1], [1, 1]] 
x=4 y=1 answer=[[1], [1, 1], [1, 2, 1]] 
x=4 y=2 answer=[[1], [1, 1], [1, 2, 1]] 
x=5 y=1 answer=[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] 
x=5 y=2 answer=[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] 
x=5 y=3 answer=[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]] [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: