- 題目描述:
-
大家都知道斐波那契數列,現在要求輸入一個整數n,請你輸出斐波那契數列的第n項。斐波那契數列的定義如下:
?
- 輸入:
-
輸入可能包含多個測試樣例,對于每個測試案例,
輸入包括一個整數n(1<=n<=70)。
?
- 輸出:
-
對應每個測試案例,
輸出第n項斐波那契數列的值。
?
- 樣例輸入:
-
3
- 樣例輸出:
-
2
看題目要求,需要輸出到70的斐波那契數列,如果用常規的遞歸,顯然層次過多,而且大部分是多余的。所以用一個數組來保持已經算出的斐波那契數列值,需要時直接從數組返回,大大節省時間。注意數組要用long long。
#include <iostream> #include <fstream> #include <vector> #include < string > #include <algorithm> #include <map> #include <stack> #include <cmath> #include <queue> #include < set > #include <list> #include <cctype> #include <stdio.h> #include <stdlib.h> #include < string .h> #define REP(i,j,k) for(int i = j ; i < k ; ++i) #define MAXV (1000) #define INF (0x6FFFFFFF) using namespace std; long long ans[ 80 ]; long long fac( int x) { if (x== 0 ) return 0 ; if (x== 1 ) return 1 ; if (ans[x]!= 0 ) return ans[x]; if (ans[x]== 0 ) { ans[x] =fac(x- 1 )+fac(x- 2 ); return ans[x]; } } int main() { // freopen("in.txt","r",stdin); memset(ans, 0 , sizeof ( long long )); int n; ans[ 1 ]= 1 ; fac( 71 ); while (~scanf( " %d " ,& n)) printf( " %lld\n " ,ans[n]); return 0 ; }
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
