Java Memoization递归方法

时间:2018-05-19 00:37:14

标签: java memoization

暂时试图找出这个问题,但无法解决这个问题。

问题:鉴于以下方法。通过记忆优化它。

public static long cat(int n) {
    if (n == 0)
        return 1;
    long result = 0;
    for (int i = 0; i < n; i++) {
        result += cat(i) * cat(n - i - 1);
    }
    return result;
}

我尝试过:

private static int memCat(int n, int[] cache) {
    if (n == 0) {
        return 1;
    }

    int result = 0;

    if (cache[n] == 0) {
        for (int i = 0; i < n; i++) {
            result += memCat(i, cache) * memCat(n - i - 1, cache);
        }
        cache[n] = result;
    }

    return result;
}

我的想法是,因为内部for循环中的所有计数的结果将被保存。所以不必重复。

public static void main(String[] args) {
    System.out.println(cat(5)); //Prints 42
    System.out.println(memCat(5, new int[5 + 1])); //Prints 1 
}

我的眼睛和大脑都很累,所以这可能只是一个简单的错误。

1 个答案:

答案 0 :(得分:1)

您的实施问题是您准备cache[],但您从未使用它。这是修复,它相当简单:

int result = cache[n];
if (result == 0) {
    for (int i = 0; i < n; i++) {
        result += memCat(i, cache) * memCat(n - i - 1, cache);
    }
    cache[n] = result;
}

现在,cache的值在之前计算时会返回,因为result在输入条件之前会被赋值为cache[n]

相关问题