You are given an integer n, your task is to generate the first n rows of Pascal's Triangle and return it as a list of lists.
Pascal's triangle is a triangular array of numbers where each number is the sum of the two numbers above it.
The first few rows of Pascal's triangle are:
1
1 1
1 2 1
1 3 3 1
Example:
Input: n = 5
Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
Output: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
Algorithm:
- Initialize an empty list of lists
ansto store the rows of Pascal's Triangle. - Create two lists
lsandprev.prevwill be used to store the previous row of Pascal's Triangle, andlswill be used to generate the current row. - Iterate from
iequals 0 ton - 1to generate each row of Pascal's Triangle:- Create a new empty list
lsto represent the current row. - Iterate from
jequals 0 toito generate the elements of the current row:- If
jis 0 orjis equal toi, add1to thelslist because the first and last elements of each row are always1. - Otherwise, add the sum of the corresponding elements from the previous row (
prev) to thelslist.
- If
- Set
prevtolsto prepare for the next iteration. - Add the
lslist (representing the current row) to theanslist.
- Create a new empty list
- Return the
anslist containing all the rows of Pascal's Triangle up ton.
Code Implementation:
import java.util.ArrayList;
import java.util.List;
public class PascalTriangle {
public static List<List<Integer>> generate(int n) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ls, prev = new ArrayList<>();
for (int i = 0; i < n; i++) {
ls = new ArrayList<>();
for (int j = 0; j <= i; j++) {
if (j == 0 || j == i) {
ls.add(1);
} else {
ls.add(prev.get(j - 1) + prev.get(j));
}
}
prev = ls;
ans.add(ls);
}
return ans;
}
// driver method
public static void main(String[] args) {
int n = 5;
System.out.println(generate(n));
}
}
Output:
[[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]
Complexity Analysis:
Time Complexity: O(n2), where n is the number of rows.
Space Complexity: O(n2)
If you want to contribute such articles to solutions2coding.com please click here. Thank you!
Tags:
Pascal's Triangle
