-
Notifications
You must be signed in to change notification settings - Fork 2
/
PascalsTriangle.java
58 lines (41 loc) · 1 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.c15;
import java.util.ArrayList;
import java.util.List;
public class PascalsTriangle {
public static List<List<Integer>> pascalsTriangle( int numRows){
List<List<Integer>> list = new ArrayList<List<Integer>>();
List<Integer> lastList = new ArrayList<Integer>();
for(int i=1;i<=numRows;i++){
if (i==1){
lastList.add(1);
list.add(lastList);
}else{
List<Integer> newList = new ArrayList<Integer>();
for(int j=0;j<i;j++){
if (j ==0){
newList.add(1);
}else if (j+1==i){
newList.add(1);
}else{
newList.add(lastList.get(j-1) + lastList.get(j));
}
}
list.add(newList);
lastList = newList;
}
}
return list;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<List<Integer>> list = pascalsTriangle(5);
for(List<Integer> subList: list){
for(int v:subList)
System.out.print(v+",");
System.out.println();
}
}
}