我希望这段代码能够打印出Pascal三角形,我需要让generate()的输出为List<List<Integer>>
我一直在苦苦挣扎太多,因为我不习惯迭代并将值分配给列表列表。你能帮我解决一下吗?我不是在寻找花哨的解决方案!
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PascalTriangle {
public static long biCoeff(int n, int k) {
if (n==k) {
return (long) 1;
}
if (n==0) {
return (long) n;
}
return (biCoeff(n-1, k-1)+biCoeff(n-1,k));
}
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> l = new ArrayList<>();
for (int i=0; i<numRows; i++) {
for (int j=0; j<l.get(i).size(); j++) {
l.get(i).add((int) biCoeff(numRows, j));
}
}
return l;
}
public static void main(String[] args){
generate(5);
}
}
错误:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at PascalTriangle.generate(PascalTriangle.java:25)
at PascalTriangle.main(PascalTriangle.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
答案 0 :(得分:4)
您必须先添加List
才能添加项目。
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> l = new ArrayList<>();
for (int i=0; i<numRows; i++){
l.add(new List<Integer>()); // add this line
//l.get(i).add((int) biCoeff(numRows, i));
for (int j=0; j<l.get(i).size(); j++) {
l.get(i).add((int) biCoeff(numRows, j));
}
}
return l;
}
实际上这段代码不会编译,因为List
是一个接口而你无法创建它的实例。
您必须选择一个实现List
的类,并使用它而不是new List<Integer>()
。例如,new java.util.ArrayList<Integer>()
答案 1 :(得分:2)
请尝试以下生成方法代码:
public static List<List<Integer>> generate(int numRows) {
List<List<Integer>> l = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; i++) {
l.add(i, new ArrayList<Integer>());
for (int j = 0; j <= i; j++){
l.get(i).add((int) biCoeff(numRows, j));
}
}
return l;
}
输出:
[[1],[1,5],[1,5,10],[1,5,10,10],[1,5,10,10,5]]
您可以拥有的其他模式是(每行末尾有1个):
import java.util.ArrayList;
import java.util.List;
public class Pascal {
static List<List<Integer>> l = new ArrayList<List<Integer>>();
public static void main(String[] args) {
int noOfRows = 5;
int counter = 0;
List<Integer> list = new ArrayList<Integer>();
list.add(1);
generate(list, counter, noOfRows);
System.out.println(l);
}
public static List<Integer> generate(List<Integer> list, int counter, int noOfRows) {
l.add(list);
List<Integer> tempList = new ArrayList<Integer>();
tempList.add(1);
for (int i = 1; i < list.size(); i++) {
tempList.add(list.get(i) + list.get(i - 1));
}
tempList.add(1);
if (counter != noOfRows)
generate(tempList, ++counter, noOfRows);
return tempList;
}
}
输出:
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1],[1,5,10] ,10, 5,1]]