给定 numRows, 生成帕斯卡三角形的前 numRows 行。
例如, 给定 numRows = 5,
返回
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
详见:https://leetcode.com/problems/pascals-triangle/description/
Java实现:
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(numRows==0){
return res;
}
List<Integer> row = new ArrayList<>();
//ArrayList中的set(index, object)和add(index, object)的区别:set:将原来index位置上的object的替换掉;add:将原来index位置上的object向后移动
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));
}
return res;
}
}