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]
]
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
if(numRows == 0) return triangle;
//存储Pascal's Triangle的第一行
triangle.add(new ArrayList<Integer>());
triangle.get(0).add(1);
//使用上一行生成下一行
for(int i=1; i < numRows; ++i) {
List<Integer> preRow = triangle.get(i-1);
List<Integer> newRow = new ArrayList<Integer>();
newRow.add(1);
for(int j=1; j < i; ++j)
newRow.add(preRow.get(j-1) + preRow.get(j));
newRow.add(1);
triangle.add(newRow);
}
return triangle;
}
//计算得到左边一半
for(int j = 1; j <= i/2; ++j)
newRow.add(preRow.get(j-1) + preRow.get(j));
//复制得到右边一半
for(int j = (i - 1)/2; j > 0; --j)
newRow.add(newRow.get(j));