Skip to content

Commit ded7b99

Browse files
author
Prashant Jain
committed
Starting linked list
1 parent 96b35f5 commit ded7b99

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package in.knowledgegate.dsa.linkedlist;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
* Given an integer numRows, return the first numRows of Pascal's triangle.
8+
* In Pascal's triangle, each number is the sum of the two numbers directly above it as shown.
9+
*
10+
* Example 1:
11+
* Input: numRows = 5
12+
* Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
13+
*
14+
* Example 2:
15+
* Input: numRows = 1
16+
* Output: [[1]]
17+
*
18+
*
19+
* Constraints:
20+
* 1 <= numRows <= 30
21+
*/
22+
public class PascalTriangle {
23+
public List<List<Integer>> generate(int numRows) {
24+
List<List<Integer>> result = new ArrayList<>();
25+
List<Integer> prev = new ArrayList<>();
26+
prev.add(1);
27+
result.add(prev);
28+
29+
for (int i = 1; i < numRows; i++) {
30+
List<Integer> curr = new ArrayList<>();
31+
curr.add(1);
32+
for (int j = 1; j < prev.size(); j++) {
33+
curr.add(prev.get(j) + prev.get(j - 1));
34+
}
35+
curr.add(1);
36+
result.add(curr);
37+
prev = curr;
38+
}
39+
return result;
40+
}
41+
}

0 commit comments

Comments
 (0)