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] ]
Java Code
public List> generate(int numRows) { List
> res = new ArrayList
>(); List
first = new ArrayList (); if(numRows < 1) return res; first.add(1); res.add(first); for(int i = 1; i < numRows; i++){ List prev = new ArrayList (); prev = res.get(i - 1); List curr = new ArrayList (); for(int j = 0; j <= prev.size(); j++){ int num = 0; if(j < prev.size()) num += prev.get(j); if(j > 0) num += prev.get(j-1); curr.add(num); } res.add(curr); } return res; }
No comments:
Post a Comment