【问题标题】:Fibonacci using Dynamic programming使用动态规划的斐波那契
【发布时间】:2016-08-07 19:16:56
【问题描述】:

我正在尝试编写稍微修改的斐波那契。

这里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 方法来做。

【问题讨论】:

  • 您能否编辑您的问题以更具体地说明您的问题。举例说明您期望获得什么以及您实际获得什么。
  • 在代码中加入一些 cmets 使其更易理解

标签: java recursion dynamic-programming fibonacci


【解决方案1】:

您的代码中有逻辑错误。

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;

【讨论】:

  • 那是因为我用递减的索引递归地调用斐波那契函数。
  • @Zeus 您的代码只有在 firstsecond 始终等于 0 和 1 时才是正确的。如果是这样,为什么需要传递它们?比如first = -1second = 3,你的代码是否正确?
  • 检查新代码。还假设第一个和第二个> 0
  • 这段代码给了我更多,因为在 F(6) 中给出了 F(7) 的值
  • @Zeus n 是 0 索引(从 0 开始)还是 1 索引(从 1 开始)?在我的解决方案中,我假设它是 0 索引的。否则你只需要相应地改变它。
猜你喜欢
  • 1970-01-01
  • 2021-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
相关资源
最近更新 更多