118.Pascal's Triangle

Question

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

img
In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

1
2
3
4
5
6
7
8
9
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]

Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i=0;i<numRows;i++){
List<Integer> temp = new ArrayList<>();
for(int j=0;j<i+1;j++){
if(j==0 || j==i)
temp.add(1);
else
temp.add(res.get(i-1).get(j-1)+res.get(i-1).get(j));
}
res.add(temp);
}
return res;
}
}

Running time:O(n^2)

Space:O(n^2)