题目
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5
输出:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
算法
public class P118 {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> rList = new ArrayList<>();
for(int i = 1;i<=numRows;i++){
addRows(i,rList);
}
return rList;
}
private void addRows(int numRows,List<List<Integer>> rList){
if(numRows==1){
List<Integer> tmpList = new ArrayList<>();
tmpList.add(1);
rList.add(tmpList);
}else if(numRows>1){
List<Integer> tmpList = new ArrayList<>();
tmpList.addAll(rList.get(numRows-2));
List<Integer> rTempList = new ArrayList<>();
rTempList.add(1);
for(int i = 0;i<tmpList.size()-1;i++){
int sum = tmpList.get(i)+tmpList.get(i+1);
rTempList.add(sum);
}
rTempList.add(1);
rList.add(rTempList);
}
}
}
思路:按照杨辉三角的规则对每一行进行计算即可。