Be the first user to complete this post
|
Add to List |
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:
- Initialize list row and list of lists as all_rows.
- 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.
- How we will update row -
- 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.
- See the walk-through below
Output:
[1] [1, 1] [1, 2, 1] [1, 3, 3, 1] [1, 4, 6, 4, 1]