你如何使Ackermann功能“学习”?

时间:2015-10-10 17:16:35

标签: java recursion

如何让以下Ackermann函数“学习”并记住之前迭代的结果,以便它不会反复重新计算相同的内容?例如:它应该知道无论何时给出输入(2,2),它应该返回7而不再运行计算。

public static BigInteger ackermann(BigInteger a, BigInteger b) {
    if (a.equals(BigInteger.ZERO)) {
        return b.add(BigInteger.ONE);
    }
    if (b.equals(BigInteger.ZERO)) {
        return ackermann(a.subtract(BigInteger.ONE),BigInteger.ONE);
    }
    return ackermann(a.subtract(BigInteger.ONE), ackermann(a, b.subtract(BigInteger.ONE)));
}

1 个答案:

答案 0 :(得分:1)

使用Java 8查看memoization:https://dzone.com/articles/java-8-automatic-memoization。这是迄今为止实现目标的最优雅方式。

相关问题