/**
* if # of rows is less than 3 then return the corresponding arraylist
* else
* first add(1) to the beginning of the list
* then rest can be drived by the sum of the previous line elements
* lastly add(1) to the end of the list
*/
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> pt = new ArrayList<List<Integer>>();
if (numRows == 0) return pt;
// initialization
pt.add(new ArrayList<Integer>());
pt.get(0).add(1);
for (int i=2; i<=numRows; i++) {
pt.add(new ArrayList<Integer>());
pt.get(i-1).add(1);
for (int j=2; j<=i-1; j++)
pt.get(i-1).add(pt.get(i-2).get(j-2)+pt.get(i-2).get(j-1));
pt.get(i-1).add(1);
}
return pt;
}
}
Leetcode 118. Pascal's Triangle
最新推荐文章于 2024-02-01 18:23:29 发布