Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
就是求平方和的各项系数,给5的时候就是(x+1)5次方的各项系数
边界情况:
numRows = 0时输出空
之后就是循环0到numRows-1,每一行首尾是1,中间依次是上一行的两两项的和
- 出错点:
for里面不能再次定义外面已经定义的tmp
代码:
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (numRows == 0) {
return result;
}
ArrayList<Integer> tmp = new ArrayList<>();
tmp.add(1);
result.add(tmp);
for(int i = 1; i < numRows; i++) {
tmp = new ArrayList<>();
tmp.add(1);
for(int j = 1; j < result.get(i-1).size(); j++) {
tmp.add(result.get(i-1).get(j-1) + result.get(i-1).get(j));
}
tmp.add(1);
result.add(tmp);
}
return result;
}