BiruLyu
6/20/2017 - 4:31 AM

## 118. Pascal's Triangle(1st).java

``````"""
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]
]

TESTCASES:
Input:
0
1
2
3
4
5

Output:
[]
[[1]]
[[1],[1,1]]
[[1],[1,1],[1,2,1]]
[[1],[1,1],[1,2,1],[1,3,3,1]]
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
"""
class Solution(object):
def generate(self, numRows):
"""
:type numRows: int
:rtype: List[List[int]]
"""
res = [];

if numRows == 0:
return res;

res.append([1]);
for i in range(1,numRows):
temp = [];
temp.append(1);
j = 0;
while(j < i - 1):
temp.append(res[i - 1][j] + res[i - 1][j + 1]);
j += 1;
temp.append(1);
res.append(temp);

return res;
``````
``````public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (numRows <= 0) return res;
res.add(Arrays.asList(1));
for (int i = 2; i <= numRows; i++) {
List<Integer> temp = new ArrayList<Integer>();
temp.add(1);
for (int j = 0; j < res.get(i - 2).size() - 1; j++) {
temp.add(res.get(i - 2).get(j) + res.get(i - 2).get(j + 1));
}
temp.add(1);
res.add(temp);
}
return res;
}
}``````
``````public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ar = new ArrayList<List<Integer>>();
for(int i=0;i<numRows;i++){
List<Integer> no = new ArrayList<Integer>();
//System.out.println(i);
for(int j=0;j<=i;j++){
//System.out.println(i);
if(j==0 || j==i){
//System.out.println(i);
no.add(1);
}
else{
no.add(ar.get(i-1).get(j-1) + ar.get(i-1).get(j));
}
}
ar.add(no);
}
return ar;
}
}``````