我正在尝试编写稍微修改的斐波那契。
在这里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方法进行操作。
最佳答案
您的代码中存在逻辑错误。first
和second
是序列中第一项和第二项的值,而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;