forked from rahul200106/hackoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PascalsTriangle.java
39 lines (38 loc) · 1.55 KB
/
PascalsTriangle.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Pascal's Triangle
// Problem Description:
/*
Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it
*/
// Implementation:
class Solution {
public List<List<Integer>> generate(int numRows) {
// Create an array list to store the output result...
List<List<Integer>> output = new ArrayList<List<Integer>>();
// Base cases...
if (numRows <= 0) return output;
// Create an array list to store the prev triangle value for further addition...
ArrayList<Integer> prev = new ArrayList<Integer>();
// Inserting for the first row & store the prev array to the output array...
prev.add(1);
output.add(prev);
// For rest of the rows, Traverse all elements through a for loop...
for (int i = 2; i <= numRows; i++) {
// Create another array to store the current triangle value...
ArrayList<Integer> curr = new ArrayList<Integer>();
curr.add(1); //first
// Calculate for each of the next values...
for (int j = 0; j < prev.size() - 1; j++) {
// Inserting the addition of the prev arry two values...
curr.add(prev.get(j) + prev.get(j + 1)); //middle
}
// Store the number 1...
curr.add(1); //last
// Store the value in the Output array...
output.add(curr);
// Set prev is equal to curr...
prev = curr;
}
return output; // Return the output list of pascal values...
}
}