
Problem
Solution
Submissions
Pascal's Triangle
Certification: Basic Level
Accuracy: 100%
Submissions: 1
Points: 5
Write a Java program to generate the first numRows of Pascal's triangle. In Pascal's triangle, each number is the sum of the two numbers directly above it. For example, the first few rows of Pascal's triangle are:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Example 1
- Input: numRows = 5
- Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
- Explanation:
- Row 1: [1]
- Row 2: [1,1]
- Row 3: [1,2,1]
- Row 4: [1,3,3,1]
- Row 5: [1,4,6,4,1]
- Therefore, the output is [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]].
Example 2
- Input: numRows = 1
- Output: [[1]]
- Explanation:
- Row 1: [1]
- Therefore, the output is [[1]].
Constraints
- 1 ≤ numRows ≤ 30
- Time Complexity: O(numRows^2)
- Space Complexity: O(numRows^2)
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
- Create a list of lists to store the triangle
- The first row always contains a single element, 1
- For each subsequent row, calculate each element as the sum of the two elements above it
- The first and last elements of each row are always 1
- Add each generated row to the result list