【问题标题】:Reduce the space complexity of the following fibonacci algorithm [duplicate]降低以下斐波那契算法的空间复杂度
【发布时间】:2021-01-26 21:41:23
【问题描述】:

降低以下斐波那契算法的空间复杂度。

我需要这方面的帮助。我想不出任何办法来做到这一点。任何帮助将不胜感激。

public static long fibonacci (int n){
    long[] f = new long[n+1];
    f[0] = 0;
    f[1] = 1;
    for(int i = 2; i <=n; i++)
      f[i] = f[i-1] + f[1-2];
    return f[n];
}

【问题讨论】:

标签: java algorithm space-complexity


【解决方案1】:

基本上,问题出在这一行:

long[] f=new long[n+1];

这一行创建了一个需要 n+1 个 long 的长数组,这要求空间复杂度是线性的。

@tzortzik 提到的递归方法将具有相同的空间复杂度,因为每个堆栈帧都需要空间,并且您还需要 n-1 个堆栈帧。

您的情况的关键是您不需要数组。你总是只需要两个值。

毕竟,如果不使用之前的计算,就没有理由保存它们。

public static long fibonacci(int n){
    long last=0;
    long current=1;
    for(int i=1;i<n;i++){
        long tmp=current;
        current+=last;
        last=current;
    }
}

这与您的算法基本相同,但没有数组。

不是将[i] 设置为数组的[i-2][i-1] 之和,而是将current 设置为lastcurrent 之和。它没有继续处理数组,而是将last 设置为current 的先前值(由tmp 支持)。

也可以使用您刚刚将 last 添加到 current 的知识来消除临时变量,并且您可以通过再次减去它来取回该值。

public static long fibonacci(int n){
    long last=0;
    long current=1;
    for(int i=1;i<n;i++){
        current+=last;
        last=current-last;
    }
}

这不会改变复杂性,实际上,这也不会改变太多。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多