我正在尝试创建一个memoized fibonacci程序来开始学习动态编程。但是,当我运行此程序时,它总是返回0.
private static Map<Integer, Long> stored = new HashMap<>();
static
{
stored.put(0, (long) 0);
stored.put(1, (long) 0);
}
public static long memo(int n)
{
if (n==0)
{
return stored.get(0);
}
else if (n==1)
{
return stored.get(1);
}
else if (stored.containsKey(n))
{
return stored.get(n);
}
else
{
long f = ( memo(n-1) + memo(n-2) );
stored.put(n, f);
return f;
}
}
答案 0 :(得分:2)
您只插入0,加0将始终为0.
用这个替换第二个静态插入:
stored.put(1, (long) 1);
答案 1 :(得分:1)
让我为你解决这个问题
private static Map<Integer, Long> stored = new HashMap<>();
static
{
stored.put(0, 0);
stored.put(1, 1);
}
public static long memo(int n)
{
if (stored.containsKey(n))
{
return stored.get(n);
} else
{
long f = ( memo(n-1) + memo(n-2) );
stored.put(n, f);
return f;
}
}