Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
这道题按思路来就可以直接写出答案,注意参数的控制,代码如下:
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList();
for(int i = 1 ; i <= numRows;i++){
List<Integer> cur = new ArrayList();
cur.add(1);
if(i > 1){
List<Integer> pre = result.get(i-2);
for(int j = 1 ; j < i -1;j++){
int m = pre.get(j-1);
int n = pre.get(j);
cur.add(m + n);
}
cur.add(1);
}
result.add(cur);
}
return result;
}
}