【发布时间】:2020-05-31 13:28:16
【问题描述】:
我正在尝试查找三项式系数,并且我想避免在我的数组中使用负索引。在某些情况下 i 或 j 将变为负数并返回数组越界错误。无论如何我可以将包含在负索引中的数组镜像到正索引吗?
这是递归公式:Recursion Formula
我知道T(0, -1) = T(0, 1),但我该如何实现呢?
示例:
row 0: T(0, 0) = 1 , T(0, 1) = 0 ...
row 1: T(1, 0) = T(0, -1) + T(0, 0) + T(0, 1) , T(2, 0) ...
三项式系数T(n,k)是x^(n+k)在(1+x+x^2)^n的展开中的系数。
三项式三角形(中间索引为0,0左侧为负数,0右侧为正数):
注意:下面的代码从中间索引0向右遍历数组。
public class ClassNameHere {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
int k = Integer.parseInt(args[1]);
long[][] DP = new long[n + 1][k + 1];
DP[0][0] = 1;
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++) {
if (i == j || ((j == 0) && i < 2)) DP[i][j] = 1;
else if (j < -i) {
DP[i][j] = 0;
} else DP[i][j] = DP[i - 1][j];
}
}
System.out.println(DP[n][k]);
}
}
现在我可以使用我的代码获取从T(0, 0) 到T(1, 0) 的条款,但无法通过添加T(1,0) + T(1, 1) + T(1, 2) 继续超过T(2, 0)。当我尝试实现DP[i][j] = DP[i - 1][j - 1] + DP[i - 1][j] + DP[i - 1][j + 1]时,它再次返回ArrayIndexOutOfBoundsException。我认为上述语句^的实现有问题。关于如何继续进行此操作的任何建议?
【问题讨论】:
标签: java arrays multidimensional-array