我需要一些帮助,我正在编写我的Programming II课程。问题是要求用递归计算Fibonacci序列。必须将计算的斐波那契数字存储在数组中以停止不必要的重复计算并减少计算时间。递归斐波那契记忆
我设法让程序在没有数组和记忆的情况下工作,现在我试图实现这一点,并且我被卡住了。我不知道如何构建它。我已经Google和Google浏览了一些书籍,但没有找到太多的东西来帮助我解决如何实施解决方案。
import javax.swing.JOptionPane;
public class question2
{
static int count = 0;
static int [] dictionary;
public static void main(String[] args)
{
int answer;
int num = Integer.parseInt(javax.swing.JOptionPane.showInputDialog("Enter n:"));
javax.swing.JOptionPane.showMessageDialog(null,
"About to calculate fibonacci(" + num + ")");
//giving the array "n" elements
dictionary= new int [num];
if (dictionary.length>=0)
dictionary[0]= 0;
if (dictionary.length>=1)
dictionary[0]= 0;
dictionary[1]= 1;
//method call
answer = fibonacci(num);
//output
JOptionPane.showMessageDialog(null,"Fibonacci("+num+") is "+answer+" (took "+count+" calls)");
}
static int fibonacci(int n)
{
count++;
// Only defined for n >= 0
if (n < 0) {
System.out.println("ERROR: fibonacci sequence not defined for negative numbers.");
System.exit(1);
}
// Base cases: f(0) is 0, f(1) is 1
// Other cases: f(n) = f(n-1) + f(n-2)/
if (n == 0)
{
return dictionary[0];
}
else if (n == 1)
{
return dictionary[1];
}
else
return dictionary[n] = fibonacci(n-1) + fibonacci(n-2);
}
}
以上是不正确的,我的fib方法的结束是主要问题。我不知道如何让它递归地将数字添加到数组的正确部分。
您知道,从头开始设置循环中的值比使用递归快得多。如果这是家庭作业,你只能使用递归。事实上,通过这种方式来计算可以表示的最大数量非常快,它可能不需要记住值。即仅在屏幕上绘制结果将花费更长的时间。 –
我怎么会这么喜欢....这个问题具体到使用递归。一些教我们如何运作的方式我猜。 – Eogcloud
这会让它成为'[作业]'添加这个标签可以让你获得关于如何以其他方式更简单的评论。 ;) –