forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPascalsTriangle.java
More file actions
58 lines (55 loc) · 1.97 KB
/
PascalsTriangle.java
File metadata and controls
58 lines (55 loc) · 1.97 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//easy iterative solution
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> results
= new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> result = new ArrayList<Integer>();
if(numRows > 0){
result.add(1);
results.add(result);
}
for(int i = 1; i < numRows; ++i){
ArrayList<Integer> tmp = new ArrayList<Integer>();
for(int j = 0; j <= results.get(i - 1).size(); ++j){
if(j == 0 || j == results.get(i - 1).size())
tmp.add(1);
else{
tmp.add(results.get(i - 1).get(j) + results.get(i - 1).get(j - 1));
}
}
results.add(tmp);
}
return results;
}
}
//recursion solution
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
if(numRows == 0)
return results;
else if(numRows == 1){
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(1);
results.add(result);
return results;
}
else{
results = generate(numRows - 1);
ArrayList<Integer> pre = results.get(numRows - 2);
ArrayList<Integer> cur = new ArrayList<Integer>();
for(int i = 0; i < numRows; ++i){
if(i == 0 || i == numRows - 1)
cur.add(1);
else
cur.add(pre.get(i - 1) + pre.get(i));
}
results.add(cur);
return results;
}
}
}