我希望对列进行动态数组调整,下面是我的方法。但是,当迭代for循环时,我得到一个恒定的列大小为1。
private int[][] res;
private void populate(int i, int j) {
if(j == 0 || j == i) {
res[i][j] = 1;
} else {
res[i][j] = res[i-1][j-1] + res[i-1][j];
}
}
public int[][] generate(int n) {
res = new int[n][];
// This part, changing i to n gives me constant columns of size n where empty entries are zeros, keeping col size i returns me constant column of size 1
for(int i = 1; i <= res.length; i++) {
res[i-1] = new int[i];
}
for(int i = 0; i < n; i++) {
for(int j = 0; j <= i; j++) {
populate(i,j);
}
}
return res;
}
对于n = 3:
期望的输出
- [ [1],
[1,1],
[1,2,1] ]
我的输出col col i
- [ [1] ,
[1],
[1] ]
我的输出col col = 3 = n
- [ [1,0,0] ,
[1,1,0],
[1,2,1] ]
如何在不使用ArrayList的情况下获得数组的动态列大小
答案 0 :(得分:1)
嗯,你的代码对我来说当然有用:
Test1 t = new Test1();
int[][] rr = t.generate(5);
for (int[] ints : rr) {
System.out.println("[ " + Arrays.toString(ints) + "]");
}
打印出来:
[ [1]]
[ [1, 1]]
[ [1, 2, 1]]
[ [1, 3, 3, 1]]
[ [1, 4, 6, 4, 1]]