118. Pascal's Triangle
iven 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] ]

//ArrayList的add方法:如果在指定索引处有值,则全体右移,然后再插入值,如ArrayList中有[1, 1],此时add(1,2),则[1, 1]中第二个1右移,然后把2加入,得到[1, 2, 1]
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> row = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
row.add(0,1);
for (int j = 1; j < row.size() - 1; j++)
row.set(j, row.get(j) + row.get(j + 1));
res.add(new ArrayList<>(row));//必须要add new ArrayList,如果直接res.add(row),row改变,res里的row也会跟着改变
}
return res;
}
浙公网安备 33010602011771号