Optimization of the Fibonacci sequence algorithm

Source: Internet
Author: User

Do a Fibonacci algorithm problem, result run timeout

public class Solution {public    int Fibonacci (int n) {    if (n = = 0) {      return 0;    }    if (n = = 1) {      return 1;    }    Return Fibonacci (n-1) + Fibonacci (n-2);    }}

Found an article, http://blog.csdn.net/sloder/article/details/8624373

Follow the ideas that they provide:

The value of each item before the calculated item is saved, and the calculation of each item only calls the Fibonacci method once,

The number of times the Fibonacci method is actually called is only n-1, and if n=33, then the Fibonacci method is called only 32 times.

The optimized code is:

1  Public classSolution {2      Public intFibonacci (intN) {3         if(n = = 0) {4       return0;5     }6     if(n = = 1) {7       return1;8     }9     int[] Array =New int[N+1];TenArray[0] = 0; OneARRAY[1] = 1; A      for(inti = 2; i < n+1; i++) { -Array[i] = array[i-1] + array[i-2]; -     } the     returnArray[n]; -     } -}

Optimization of the Fibonacci sequence algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.