【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
- 给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList();
if (numRows <= 0) return res;
List<Integer> row1 = new ArrayList();
row1.add(1);
List<Integer> prevRow = row1;
for (int i=2; i<=numRows; i++) {
List<Integer> curRow = new ArrayList(i);
curRow.add(1);
for (int j=1; j<i-1; j++) { // 除去两边的1 中间的数字由上一列的相邻两个数字相加
curRow.add( prevRow.get(j-1) + prevRow.get(j));
}
curRow.add(1); // 将1 加上
res.add(curRow);
prevRow = curRow;
}
return res;
}
来源:oschina
链接:https://my.oschina.net/u/3737002/blog/3142667