forked from gouthampradhan/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPascalsTriangle.java
54 lines (49 loc) · 1.22 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
package array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by gouthamvidyapradhan on 25/03/2017.
*
* Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
*/
public class PascalsTriangle
{
public static void main(String[] args) throws Exception
{
System.out.println(new PascalsTriangle().getRow(3));
}
public List<Integer> getRow(int rowIndex)
{
int k = rowIndex;
if(k == 0)
return Arrays.asList(1);
else if(k == 1)
return Arrays.asList(1, 1);
else if (k == 2)
return Arrays.asList(1, 2, 1);
List<Integer> result = new ArrayList<>();
result.add(2);
k = k - 2;
int p, c;
while(k-- > 0)
{
p = 1;
int i = 0;
for(int l = result.size(); i < l; i ++)
{
c = result.get(i);
result.set(i, p + c);
p = c;
}
result.add(p + 1);
}
result.add(0, 1);
result.add(1);
return result;
}
}