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
ans
to store the rows of Pascal's Triangle. - Create two lists
ls
andprev
.prev
will be used to store the previous row of Pascal's Triangle, andls
will be used to generate the current row. - Iterate from
i
equals 0 ton - 1
to generate each row of Pascal's Triangle:- Create a new empty list
ls
to represent the current row. - Iterate from
j
equals 0 toi
to generate the elements of the current row:- If
j
is 0 orj
is equal toi
, add1
to thels
list 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 thels
list.
- If
- Set
prev
tols
to prepare for the next iteration. - Add the
ls
list (representing the current row) to theans
list.
- Create a new empty list
- Return the
ans
list 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