2017-02-15 75 views
-2

我需要将以下递归代码转换为迭代版本,并且我的脑袋被炸开。我觉得我错过了一些明显的东西。任何帮助表示赞赏。将递归函数转换为迭代版本

public static int computeRecursive(int n){ 
    if(n <= 1){ 
     return n; 
    } 
    else{ 
     return 2 * computeRecursive(n-2) + computeRecursive(n-1); 
    } 
} 
+2

那你试试这么远吗? – nachokk

+0

'return((1 << n)+1)/ 3;':) – ZhongYu

回答

1

您可以尝试下面的代码。它与斐波那契系列相似。

public static int computeRecursive(int n){ 
int a[]=new int[n]; 
a[0]=1; a[1]=1; 
for(int i=2;i<n;i++){ 
    a[i]=2*a[i-2]+a[i-1]; 
} 
return a[n-1]; 
} 
+0

非常感谢,这正是我需要的! –

2

这类似于一个迭代的斐波那契数列,在那里你在两个变量ab握住你的功能f()的初始两个值。然后,计算结果为当前N送行的前两个结果:

public static int f(int n) { 
    if (n <= 1) { 
     return n; 
    } 

    int result = 0; 
    int a = 0, // f(0) = 0 
     b = 1; // f(1) = 1 

    // start iteration at n=2 because we already have f(0) and f(1) 
    for(int i = 2; i <= n; i++) { 
     // f(n) = 2 * f(n-2) + f(n-1) 
     result = 2 * a + b; 

     // f(n-2) = f(n-1) 
     a = b; 
     // f(n-1) = f(n) 
     b = result; 
    } 

    return result; 
} 
+0

不错!你做了功课! – nachokk

+0

@nachok我对这个问题更感兴趣,而不是它是否是功课。成为OP的道德良知并不是我的责任。 –

+0

猎人,问题是那样我认为你不帮他/她做功课 – nachokk

2

在我看来这两种递归和迭代的解决方案是弱,如果你可以运用你的数学技能和制定出公式。在这种情况下,我们有:f(n)=(2 ** n - ( - 1)** n)/ 3。贝娄是你如何解决问题的。

f(0) = 0 
f(1) = 1 
f(n) = f(n-1) + 2 * f(n-2) 

So the polynomial for this recurrence is: 
r ** 2 = r + 2 

If you sole that you will get the values of r as r1 =−1 and r2 =2 

So the solution to the recurrence is on the form: 
f(n) = c1 ∗ r1 ** n + c2 ∗ r2 ** n 

To work out the values for c1 and c2 constants just use the initial condition f(0) = 0 and f(1) = 1 and you will get 
c1 = -1/3 and c2 = 1/3 

So the final formula for your iteration is 
f(n) = (-1 * (-1) ** n + 2 ** n)/3 = (2 ** n -(-1) ** n)/3. 

一旦你知道使用java或其他语言实现它的公式很容易。

public static int f(int n) { 
    return n <= 1 ? n: (Math.pow(2,n) - Math.pow(-1, n))/3; 
} 

希望它帮助

+0

抱歉我没有得到f(n)= f(n-1)= 2 * f(n -2)' –

+0

对不起,我的意思是'f(n-1)+ 2 * f(n-2)。我更新了我的答案。谢谢。 – Julian