Question

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

Solution

Key to the solution is to use two arrays, one for current list, one for previous array.

 public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows == 0)
return result;
List<Integer> prev = new ArrayList<Integer>();
prev.add(1);
result.add(prev);
while (numRows > 1) {
List<Integer> current = new ArrayList<Integer>();
int length = prev.size();
current.add(1);
for (int i = 0; i < length - 1; i++)
current.add(prev.get(i) + prev.get(i + 1));
current.add(1);
result.add(current);
prev = current;
numRows--;
}
return result;
}
}
05-11 18:02