Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

java - Reduce the space complexity of the following fibonacci algorithm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Basically, the problem is this line:

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

This line creates a long array requiring n+1 longs what requires the space complexity to be linear.

A recursive approach as @tzortzik mentioned would have the same space complexity as every stack frame requires space and you would also require n-1 stack frames.

The key in your case is that you do not need the array. You always just need two values.

After all, there is no reason for saving the previous calculations if you don't use them.

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;
    }
}

This is basically the same as your algorithm but without the array.

Instead of setting [i] to the sum of [i-2] and [i-1] of an array, it sets current to the sum of last and current. Instead of going on with the array, it sets last to the previoud value of current (backed up by tmp).

It would also be possible to eliminate the temporary variable using the knowledge that you just added last to current and you can get the value back by substracting it again.

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

This would not change the complexity and in reality, this would also not change much.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...