Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将递归函数转化为迭代函数_Java_Recursion_Iteration - Fatal编程技术网

Java 将递归函数转化为迭代函数

Java 将递归函数转化为迭代函数,java,recursion,iteration,Java,Recursion,Iteration,我需要将下面的递归代码转换成一个迭代版本,我的头脑已经崩溃了。我觉得我错过了一些显而易见的东西。感谢您的帮助 public static int computeRecursive(int n){ if(n <= 1){ return n; } else{ return 2 * computeRecursive(n-2) + computeRecursive(n-1); } } publicstaticintcomputere

我需要将下面的递归代码转换成一个迭代版本,我的头脑已经崩溃了。我觉得我错过了一些显而易见的东西。感谢您的帮助

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

如果(n你可以试试下面的代码。它类似于斐波那契级数

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];
}
publicstaticintcomputerecursive(intn){
int a[]=新的int[n];
a[0]=1;a[1]=1;

对于(int i=2;i这类似于迭代斐波那契级数,在迭代斐波那契级数中,在两个变量
a
b
中保持函数
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;
}
公共静态int f(int n){

如果(n在我看来,如果你能运用你的数学技能,算出公式,那么递归解和迭代解都很弱

在这种情况下,我们有: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;
}
公共静态int f(int n){

return n到目前为止你尝试了什么?
return((1非常感谢你,这正是我需要的!对不起,我没有得到
f(n)=f(n-1)=2*f(n-2)
对不起,我的意思是'f(n-1)+2*f(n-2).我更新了我的答案。谢谢。@nachok我对这个问题比对家庭作业更感兴趣。我的责任不是成为OP的道德良知。亨特,问题是这样我认为你没有帮助他/她做家庭作业