編程之美 裴波那楔數列

來源:互聯網
上載者:User

給出如下遞推式:

       

以上就是經典的Fibonacci數列,下面給出遞推的解法:

       

[cpp]
view plaincopyprint?
  1. int Fibonacci(int n)  
  2. {  
  3.    if(n<=0)  
  4.        return 0;  
  5.    else if(n==1)  
  6.         return 1;  
  7.    else  
  8.        return Fibonacci(n-1)+Fibonacci(n-2);  
  9.   
  10. }  

我們知道 ,以上的解法每個F(n)計算了2次,我們能不能只計算一次,做一個緩衝,當然是可以的。如下:

[cpp]
view plaincopyprint?
  1. int tmp1=1;//臨時變數,儲存中間結果  
  2. int tmp2=0;  
  3. int tmp;  
  4.   
  5. int Fibonacci(int n)  
  6. {  
  7.   int F;  
  8.    
  9.   for(int i=2;i<=n;++i)  
  10.   {  
  11.   
  12.      tmp=tmp1+tmp2;       
  13.      tmp2=tmp1;  
  14.      tmp1=tmp;  
  15.   }  
  16.   return tmp;  
  17. }  

以上採用了迴圈的方法,時間複雜度加快了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.