我遇到了以下问题:
F(n)= 0 when n = 0;
F(n)= 1 when n = 1;
F(n)= F(n-1) + F(n-2) when n>1;
我已经可以像这样递归地解决这个问题了:
int F(int n) {
if(n=0) return 0;
if(n=1) return 1;
if(n>1) return F(n-1) + F(n-2);
}
但复杂性为O(n^2)
。如何通过复杂性O(n)
来解决这个问题?
我需要阅读哪本书来解决这样的问题?
答案 0 :(得分:1)
此功能正是您所需要的。是的,这是动态编程。
static ArrayList<Double> getSeries(int n)
{
ArrayList<Double> series = new ArrayList<>();
series.add(0.0); // This is working as replacement of the F(0)
series.add(1.0); // This is working as replacement of the F(1)
double x, y;
for (int i = 1; i < n; i++)
{
x= series.get(i - 1); // This is working as replacement of the F(n-2)
y = series.get(i); // This is working as replacement of the F(n-1)
series.add(x + y);
}
return series;
}
请在此处试用此代码: - https://ideone.com/IMixm9
这里可以看到计算空间和时间的基本权衡。
在
Space Complexity :- log
Time Complexity :- 2^n
现在
Space Complexity :- n
Time Complexity :- n