public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (numRows < 0) {
return res;
}
List<Integer> level = new ArrayList<Integer>();
for (int i=0; i<numRows; i++) {
// each level starts with 1
level.add(0, 1);
// for each element besides the first and last, calculate the value by summing up previous level's jth and (j+1)th element
for (int j=1; j<level.size()-1; j++) {
level.set(j, level.get(j) + level.get(j+1));
}
// add each level to the result
res.add(new ArrayList(level));
}
return res;
}
}
Leetcode 118. Pascal's Triangle
最新推荐文章于 2024-01-06 10:33:41 发布