題目:給定一個非負整數 numRows,生成楊輝三角的前 numRows 行。
例:輸入: 5
輸出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
①觀察楊輝三角形的特點,發現其首位和末尾元素始終爲1;
②除了第一行,當前行數組元素=前一行每一個數組對應下標的元素+前一下標的元素;
③根據這個特點寫出程序即可。
//當前行數組元素=前一行每一個數組對應下標的元素+前一下標的元素
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if (numRows<0){
return list;
}
List<Integer> tmp = null;
for (int i = 1; i <= numRows; i++){//每行的元素個數
List<Integer> list0 = new ArrayList<Integer>();
for (int j = 0; j < i; j++){
//如果當前行是首位元素,則爲1
if (j==0 || j == i-1){
list0.add(1);
} else{
//中間元素爲前一數組的當前索引元素加前一索引元素
list0.add(tmp.get(j-1)+tmp.get(j));
}
}
list.add(list0);
tmp = list0;//臨時list集合保存當前list0,作爲下一行的前一行
}
return list;
}