Pascal’s Triangle

Monisha Mathew
1 min readJun 5, 2019

--

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

You may view the full question here.

Approach 1: Let’s dive right into the code —

//Approach 1:
//Runtime: 0ms
//Memory usage: 34MB
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList();
if(numRows>=1){
List<Integer> list = new ArrayList();
list.add(1);
result.add(list);
}

for(int i = 2; i<=numRows; i++){
compute(result, i-1);
}
return result;
}

private void compute(List<List<Integer>> result, int row){
List<Integer> prev = result.get(row-1);
List<Integer> curr = new ArrayList();
curr.add(1);
for(int i = 1; i<=row-1; i++){
curr.add(prev.get(i-1) + prev.get(i));
}
curr.add(1);
result.add(curr);
}
}

Find more posts here.

Cheers & Chao!

--

--