-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathPascal's Triangle.java
More file actions
44 lines (40 loc) · 1.23 KB
/
Pascal's Triangle.java
File metadata and controls
44 lines (40 loc) · 1.23 KB
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
40
41
42
43
44
/*
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
*/
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (numRows == 0) {
return result;
}
if (numRows == 1) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(1);
result.add(list);
return result;
}
ArrayList<ArrayList<Integer>> parentResult = generate(numRows - 1);
ArrayList<Integer> parentList = parentResult.get(numRows - 2);
ArrayList<Integer> curList = new ArrayList<Integer>();
curList.add(1);
for (int i = 1; i < numRows - 1; i++) {
curList.add(parentList.get(i - 1) + parentList.get(i));
}
curList.add(1);
// result = parentResult;
// result.add(curList);
parentResult.add(curList);
return parentResult;
}
}