Skip to content

Commit fb20289

Browse files
committed
finished Pascal's Triangle II
1 parent 5d25f01 commit fb20289

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/Pascal's Triangle II/.DS_Store

6 KB
Binary file not shown.
+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/*
2+
Given an index k, return the kth row of the Pascal's triangle.
3+
4+
For example, given k = 3,
5+
Return [1,3,3,1].
6+
7+
Note:
8+
Could you optimize your algorithm to use only O(k) extra space?*/
9+
10+
public class Solution {
11+
public ArrayList<Integer> getRow(int rowIndex) {
12+
// Start typing your Java solution below
13+
// DO NOT write main() function
14+
ArrayList<ArrayList<Integer>> triangle = new ArrayList<ArrayList<Integer>>();
15+
for(int i = 0; i <= rowIndex; i++){
16+
ArrayList<Integer> tmp = new ArrayList<Integer>();
17+
tmp.add(1);
18+
if(i > 0){
19+
for(int j = 0; j < triangle.get(i - 1).size() - 1; j++){
20+
tmp.add(triangle.get(i - 1).get(j) + triangle.get(i - 1).get(j + 1));
21+
}
22+
tmp.add(1);
23+
}
24+
triangle.add(tmp);
25+
}
26+
return triangle.get(rowIndex);
27+
}
28+
}
29+
30+
31+
//********************O(k) Solution
32+
/*
33+
如果没有这个O(k)空间的限制,那么可以一行一行迭代生成。如果要直接生成第i行,假设生成k=3,可以这样考虑这样的一个过程:
34+
1 0 0 0 k = 0
35+
1 1 0 0 k = 1
36+
1 1 1 0
37+
1 2 1 0 k = 2
38+
1 2 1 1
39+
1 2 3 1
40+
1 3 3 1 k = 3
41+
上述过程实际上就是一个in-place的迭代过程。每当生成下一行的时候,首先数组相应位置1,然后从右向左计算每一个系数。
42+
http://blog.csdn.net/abcbc/article/details/8982651
43+
*/
44+
45+
public ArrayList<Integer> getRow(int rowIndex) {
46+
// Start typing your Java solution below
47+
// DO NOT write main() function
48+
ArrayList<Integer> result = new ArrayList<Integer>(rowIndex + 1);
49+
for (int i = 0; i <= rowIndex; i++) {
50+
result.add(0);
51+
}
52+
result.set(0, 1);
53+
for (int i = 1; i <= rowIndex; i++) {
54+
result.set(i, 1);
55+
for (int j = i - 1; j > 0; j--) {
56+
result.set(j, result.get(j) + result.get(j - 1));
57+
}
58+
}
59+
return result;
60+
}

0 commit comments

Comments
 (0)