-
Notifications
You must be signed in to change notification settings - Fork 0
118. Pascal's Triangle
Jacky Zhang edited this page Aug 16, 2016
·
1 revision
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]
]
Array类题目。
Pascal's triangle的特点是每一层数字是上一层两个数字之和。 注意点为处理每一层前后两个1。
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
for(int i = 0; i < numRows; i++) {
List<Integer> row = new ArrayList<Integer>();
row.add(1);
for(int j = 1; j < i; j++) {
row.add(res.get(i-1).get(j-1) + res.get(i-1).get(j));
}
if(i > 0) row.add(1);
res.add(row);
}
return res;
}
}