
Problem
Solution
Submissions
Pascal’s Triangle
Certification: Basic Level
Accuracy: 66.67%
Submissions: 3
Points: 10
Write a C++ program to print Pascal's triangle up to the given number of rows n.
Example 1
- Input: n = 5
- Output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1 - Explanation:
- Step 1: First row of Pascal's triangle is always [1].
- Step 2: For subsequent rows, each element is the sum of the two elements above it.
- Step 3: For row 2, we get [1, 1].
- Step 4: For row 3, we calculate [1, 1+1, 1] = [1, 2, 1].
- Step 5: For row 4, we calculate [1, 1+2, 2+1, 1] = [1, 3, 3, 1].
- Step 6: For row 5, we calculate [1, 1+3, 3+3, 3+1, 1] = [1, 4, 6, 4, 1].
- Step 7: Print all rows up to n = 5.
Example 2
- Input: n = 3
- Output:
1
1 1
1 2 1 - Explanation:
- Step 1: First row of Pascal's triangle is always [1].
- Step 2: For subsequent rows, each element is the sum of the two elements above it.
- Step 3: For row 2, we get [1, 1].
- Step 4: For row 3, we calculate [1, 1+1, 1] = [1, 2, 1].
- Step 5: Print all rows up to n = 3.
Constraints
- 1 ≤ n ≤ 20
- Time Complexity: O(n²)
- Space Complexity: O(n²)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use nested loops to compute each element based on combinations.
- Each element in a row can be derived from the previous element.