Java 用记忆法求二项系数

Java 用记忆法求二项系数,java,exception,recursion,binomial-coefficients,Java,Exception,Recursion,Binomial Coefficients,我写了一个函数,使用memorizaion方法递归计算n和k的二元系数项,我得到了一个OutOfBoundException当我执行时,我很高兴听到一些关于我所犯错误的说明。 谢谢大家 public class Binomial { public static void main(String[] args) { int n = Integer.parseInt(args[0]); int k = Integer.parseInt(args[1]);

我写了一个函数,使用memorizaion方法递归计算n和k的二元系数项,我得到了一个
OutOfBoundException
当我执行时,我很高兴听到一些关于我所犯错误的说明。 谢谢大家

public class Binomial {

    public static void main(String[] args) {

        int n = Integer.parseInt(args[0]);
        int k = Integer.parseInt(args[1]);
        StdOut.print(binomial(n, k));
    }

    /**
     * Recursively calculates the binomical coefficient term of n and k using
     * the memoizazion methood
     *
     * @param n
     *            the upper nonnegative integer of the binomical coefficient
     * @param k
     *            the lower nonnegative integer of the binomical coefficient
     * @returns the computed binomical coefficient
     */
    public static long binomial(int n, int k) {
        long[][] mem = new long[n + 1][k + 1];
        for (int i = 0; i <= n; i++) {
            for (int j = 0; j <= n; j++) {
                mem[i][j] = -1;
            }
        }
        return binomial(n, k, mem);
    }

    public static long binomial(int n, int k, long[][] mem) {
        if (k > n)
            return 0;
        if (k == 0 || n == 0)
            return 1;
        if (mem[n - 1][k] == -1) {
            mem[n - 1][k] = binomial(n - 1, k, mem);
        }
        if (mem[n - 1][k - 1] == -1) {
            mem[n - 1][k - 1] = binomial(n - 1, k - 1, mem);
        }
        return (mem[n - 1][k] + mem[n - 1][k - 1]);
    }
}
公共类二项式{
公共静态void main(字符串[]args){
int n=Integer.parseInt(args[0]);
intk=Integer.parseInt(args[1]);
标准打印(二项式(n,k));
}
/**
*使用
*回忆录法
*
*@param n
*二项系数的上非负整数
*@param k
*二项系数的下非负整数
*@返回计算出的二项式系数
*/
公共静态长二项式(int n,int k){
long[]mem=新长[n+1][k+1];

对于(int i=0;i一个非常简单的错误导致函数
公共静态长二项式(int n,int k)
更改
n
内部
对于
k
,我的意思是:

public static long binomial(int n, int k) {
    long[][] mem = new long[n + 1][k + 1];
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= k; j++) {
            mem[i][j] = -1;
        }
    }
    return binomial(n, k, mem);
}
公共静态长二项式(int n,int k){
long[]mem=新长[n+1][k+1];

对于(int i=0;i),您应该进行一些调试。