Given numRows, generate the first numRows of Pascal's triangle.
Each listp is generated by its previous list q . Except for the first and the last element,p[i]=q[i−1]+q[i]
Each list
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows == 0)
return result;
// Generate the first list
List<Integer> previous = new ArrayList<Integer>(1);
previous.add(1);
result.add(previous);
// A new list is generated base on its previous list
for (int i = 2; i <= numRows; i++) {
List<Integer> current = new ArrayList<Integer>(i);
current.add(1);
for (int j = 1; j < previous.size(); j++)
current.add(previous.get(j-1) + previous.get(j));
current.add(1);
result.add(current);
previous = current;
}
return result;
}
Read full article from LeetCode - Pascal's Triangle | Darren's Blog
No comments:
Post a Comment