Be the first user to complete this post

  • 0
Add to List
Beginner

504. What is a Pascal Triangle?

Given a number N, write a program to print the first N lines of the Pascal triangle.

Pascal Triangle:

Note: In Pascal's triangle, each number is the sum of the two numbers directly above it. 

(Image reference: Wiki)

Approach:

  1. Initialize list row and list of lists as all_rows
  2. We will keep updating the list row by adding more numbers and after each iteration, create a copy of the row and add it to the all_rows.
  3. How we will update row
    1. For each iteration of N, add 1 at index 0. Now iterate the rest of the elements in the list row, keep adding elements in pairs, starting from j=1, and set the sum at index j.
  4. See the walk-through below
Pascal Triangle
 

 

Output:

 

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