Given a non-negative integer n, print the first n rows of Pascal’s triangle.

Each number in Pascal’s triangle is constructed by adding the two numbers diagonally above, where blank entries being interpreted as 0. For instance, the first eight rows of Pascal’s triangle are depicted in the diagram below.

Pascal Triangle

For example,

Input: n = 3
Output: [[1], [1, 1], [1, 2, 1]]
 
Input: n = 5
Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]

We can easily solve this problem using dynamic programming. The idea is to calculate the subsequent row of Pascal’s triangle using the values of its previous row. With the exception of the first and last, each member of the row can be calculated by adding the element directly above it and the preceding element before the top element. The first and last elements of each row are always ones, and the first row only has one element, which is also one.

 
Following is the C++, Java, and Python implementation based on the idea:

C++


Download  Run Code

Output:

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Java


Download  Run Code

Output:

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

Python


Download  Run Code

Output:

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

The time complexity of the above solution is O(n) and requires O(n) extra space.