題目
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] ]分析
逐層構造,注意邊界條件。
代碼
import java.util.ArrayList; public class PascalTriangle { public ArrayList> generate(int numRows) { ArrayList> results = new ArrayList>(); if (numRows <= 0) { return results; } ArrayListfirstRow = new ArrayList (); firstRow.add(1); results.add(firstRow); ArrayList lastRow = firstRow; for (int i = 1; i < numRows; ++i) { ArrayList row = new ArrayList (); row.add(1); for (int j = 1; j < i - 1; ++j) { row.add(lastRow.get(j - 1) + lastRow.get(j)); } row.add(1); results.add(row); lastRow = row; } return results; } }