Space 带记忆的递归斐波那契的复杂性?

Space complexity for recursive Fibonacci with memoization?

我有这两种方法可以找到给定数字 'n' 的斐波那契数列。一个使用记忆。

我想知道这两种方法的 Space 复杂度有何不同:

    public static int fib(int n, int[] mem){

    if(n ==0 || n ==1 ){
        return n;
    }

    if(mem[n] > 0 ) {
        return mem[n]);
    }

    mem[n] = fib(n-1,mem) + fib(n-2,mem);

    return mem[n]; 

}

没有记忆:

public static int fib(int n){

    if(n ==0 || n ==1 ){
        return n;
    }

   return fib(n-1) + fib(n-2);


}

直接内存使用是不言而喻的——使用记忆化,fib 中的每个值将只计算一次,因此您的 space 复杂度将为 o(n),其中 n 是 fib 的输入数字(记忆数组将包含 n 个数字)。

没有记忆 - 不需要额外的内存(缺点是很多冗余计算)。

Is the memoization array, which is passed on to each of the recursive calls the same array ..or a copy of that array? In case the copy of the array is passed... the space complexity would be > O(n).

您正在将相同的数组引用传递给您的递归调用。

这意味着您的 space 复杂度为 o(n)。如果您要创建一个新数组并传递它,您的记忆将无法工作,因为您必须将更新后的新数组的结果与之前的 one/s.

合并