我试图使用11的幂来生成pascal的三角形,但它只能工作到4,并且需要修改4个代码以实现三角形的更多部分。答案的任何线索(如果可能通过这种方法)是值得赞赏的。
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> a=new ArrayList<List<Integer>>();
for(int i=0;i<numRows;i++){
List<Integer> b = new ArrayList<Integer>(i);
int c=(int)(Math.pow(11,i));
while(c>0){
int d=c%10;
b.add(d);
c=c/10;
}
a.add(b);
}
return a;
}
}
可悲的是,11的力量达到了第5行并且因为重新组合而在那里结束(有10个所以它“携带”)。
例:期望11 ^ 5 = 1 | 5 | 10 | 10 | 5 | 1但我们得到11 ^ 5 = 161051
您可以按照不同的方法打印pascal三角形。
您正在以相反的顺序向arraylist添加数字,因此在将内部列表添加到外部之前,只需将其反转即可。
while(c>0){
int d=c%10;
b.add(d);
c=c/10;
}
Collections.reverse(b);
a.add(b);