題目:給定 numRows,生成楊輝三角的前 numRows 行。例如 numRows = 5 時輸出:
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
逐行構造,利用上一行的值計算當前行:首尾為 1,中間元素等於上一行對應位置及其前一位之和。注意邊界條件(numRows <= 0 返回空列表)。
import java.util.ArrayList;
import java.util.List;
public class PascalTriangle {
public List> generate(int numRows) {
List> results = new ArrayList<>();
if (numRows <= 0) return results;
List firstRow = new ArrayList<>();
firstRow.add(1);
results.add(firstRow);
List lastRow = firstRow;
for (int i = 1; i < numRows; ++i) {
List row = new ArrayList<>();
row.add(1);
for (int j = 1; j < i; ++j) {
row.add(lastRow.get(j - 1) + lastRow.get(j));
}
row.add(1);
results.add(row);
lastRow = row;
}
return results;
}
}