Input: N = 5, r = 5, c = 3
Output: Element at position (r, c): 6
N-th row of Pascal’s triangle: 1 4 6 4 1
First n rows of Pascal’s triangle:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Explanation: Pascal triangle for first 5 rows is shown above.
Input: N = 1, r = 1, c = 1
Output: Element at position (r, c): 1
N-th row of Pascal’s triangle: 1
First n rows of Pascal’s triangle:
1
To generate the entire Pascal’s Triangle for the first N rows, we can start with the first row containing a single 1 and iteratively build each subsequent row using the property that every element (except the first and last) is the sum of the two elements directly above it from the previous row. The first and last elements of each row are always 1. By storing the previous row, we can calculate the next row easily. This process continues until we have constructed all N rows, resulting in the complete Pascal’s Triangle structure.
import java.util.*;
// Class containing Pascal's Triangle generation logic
class Solution {
// Function to generate Pascal's Triangle up to numRows
public List<List<Integer>> generate(int numRows) {
// Result list to hold all rows
List<List<Integer>> triangle = new ArrayList<>();
// Loop for each row
for (int i = 0; i < numRows; i++) {
// Create a row with size (i+1)
List<Integer> row = new ArrayList<>(Collections.nCopies(i + 1, 1));
// Fill elements from index 1 to i-1 (middle values)
for (int j = 1; j < i; j++) {
// Each element = sum of two elements above it
row.set(j, triangle.get(i - 1).get(j - 1) +
triangle.get(i - 1).get(j));
}
// Add current row to the triangle
triangle.add(row);
}
return triangle;
}
}
public class Main {
public static void main(String[] args) {
Solution obj = new Solution();
int n = 5;
// Generate and print Pascal's Triangle
List<List<Integer>> result = obj.generate(n);
for (List<Integer> row : result) {
for (Integer val : row) System.out.print(val + " ");
System.out.println();
}
}
}
Time Complexity: O(N^2) , we generate all the elements in first N rows sequentially one by one.
Space Complexity: O(N^2) , additional space used for storing the entire pascal triangle.
To print the Nth row of the pascal triangle we can take advantage of the relationship between Nth element and binomial coefficients.
In a pascal's triangle, the Nth row contains the binomial coefficients C(N-1, 0), C(N-1, 1) and so on till C(N-1, N-1). Thus we can simply calculate all these values to return the Nth row of pascal triangle.
Instead of computing full factorials, we can start with the first value as 1, and use the relation C(n, k) = C(n, k−1) × (n−k+1) / k to compute the next value from the previous one in constant time.