给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
解
首先注意边界值处理(被坑了一万次),然后使用List中嵌套List时,对内部List做修改是,之前add的值也会发生修改,所以每次需要新new一个List出来(可能有更好的方式,等以后发掘)。还是对java了解不够深入,一直卡在这里,还是得多注重基础知识。
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if(numRows==0)
return res;
List<Integer> temp = new ArrayList<>();
temp.add(1);
res.add(temp);
if(numRows==1)
return res;
print(res);
List<Integer> temp2 = new ArrayList<>();
temp2.add(1);
temp2.add(1);
res.add(temp2);
if(2==numRows)
return res;
for(int i = 2;i<=numRows;i++) {
temp = new ArrayList<>();
for(int j = 0;j<=i;j++) {
if(0==j||j==i)
temp.add(1);
else {
int t = res.get(i-1).get(j-1) + res.get(i-1).get(j);
temp.add(t);
}
}
res.add(temp);
}
return res;
}