Eog*_*oud 13 java math recursion fibonacci
我需要一些帮助,我正在为Universiy的Programming II课程编写一个程序.问题是要求使用递归计算Fibonacci序列.必须将计算出的斐波纳契数存储在一个数组中,以阻止不必要的重复计算并减少计算时间.
我设法让程序在没有数组和记忆的情况下工作,现在我正在尝试实现它并且我被卡住了.我不确定如何构建它.我用谷歌搜索并略读了一些书,但没有找到太多帮助我解决如何实施解决方案.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
以上是不正确的,我的fib方法的结束是主要问题.我不知道如何将数字递归地添加到数组的正确部分.
Joa*_*uer 20
您需要区分字典中已计算的数字和未计算的数字,而您目前不需要:您总是重新计算数字.
if (n == 0)
{
// special case because fib(0) is 0
return dictionary[0];
}
else
{
int f = dictionary[n];
if (f == 0) {
// number wasn't calculated yet.
f = fibonacci(n-1) + fibonacci(n-2);
dictionary[n] = f;
}
return f;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
public static int fib(int n, Map<Integer,Integer> map){
if(n ==0){
return 0;
}
if(n ==1){
return 1;
}
if(map.containsKey(n)){
return map.get(n);
}
Integer fibForN = fib(n-1,map) + fib(n-2,map);
map.put(n, fibForN);
return fibForN;
}
Run Code Online (Sandbox Code Playgroud)
与上述大多数解决方案类似,但使用地图代替.
程序n使用记忆功能打印第一个斐波那契数字。
int[] dictionary;
// Get Fibonacci with Memoization
public int getFibWithMem(int n) {
if (dictionary == null) {
dictionary = new int[n];
}
if (dictionary[n - 1] == 0) {
if (n <= 2) {
dictionary[n - 1] = n - 1;
} else {
dictionary[n - 1] = getFibWithMem(n - 1) + getFibWithMem(n - 2);
}
}
return dictionary[n - 1];
}
public void printFibonacci()
{
for (int curr : dictionary) {
System.out.print("F[" + i++ + "]:" + curr + ", ");
}
}
Run Code Online (Sandbox Code Playgroud)