Fibonacci使用动态编程

时间:2016-04-15 17:36:11

标签: java recursion dynamic-programming fibonacci

我正在尝试对稍微修改过的Fibonacci进行编码。

此处n = (n-1)^2 + (n-2)

这是我的代码,

public static int fibonacci(int first, int second, int n){
    int[] memo = new int[n + 1];
    for(int i=0; i<= n; i++){
        memo[i] = -1;
    }
    return fibonacci(first, second, n, memo);

}

public static int fibonacci(int first, int second, int n, int[] memo){
    if(n == first || n == second) return n;

    if(memo[n] < 0) memo[n] =  (int)Math.pow(fibonacci(first, second, n-1, memo), 2) + fibonacci(first, second, n-2, memo);

    return memo[n];
}

我已经尝试了几次调试,但似乎无法弄清楚问题出在哪里。该代码产生下一个数字,因此它产生F(5)的F(6)。任何帮助赞赏。 请理解,我可以交互式地解决这个问题,但这不是我想要做的。我想用这种DP方法做到这一点。

1 个答案:

答案 0 :(得分:2)

您的代码中存在逻辑错误。

firstsecond是序列中第一个和第二个词的值,n是您要查找的值的索引。但是在这里,你比较索引和值,这是错误的:

    if(n == first){
        return memo[n] = first;

    }
    if(n == second) return memo[n] = second;

应该是:

    if(n == 1){
        return memo[n] = first;

    }
    if(n == 2) return memo[n] = second;