题目:大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。n<=39
思路:可以用两种方法实现,这里递归的办法因为有太多重复的计算会超时(计算n=39,需要4s左右,题目要求1s),遂改用循环语句写(经测试n=39时,完全小于1s),下面的代码中也给出了c++中计算时间的办法之一,供参考。
费波那契数列定义如下:
- (n≧2) (from wiki)
1 #include<cstdio> 2 #include<time.h> 3 using namespace std; 4 5 class Solution { 6 public: 7 int Fibonacci(int n) { 8 int a = 0; 9 int b = 1; 10 int temp = 0; 11 if (n == 0) return 0; 12 for (int i = 1; i < n; i++) { 13 temp = b; 14 b = a + b; 15 a = temp; 16 } 17 return b; 18 } 19 int Fibonacci_rec(int n) { 20 if (n == 0) return 0; 21 if (n == 1) return 1; 22 return Fibonacci_rec(n - 1) + Fibonacci_rec(n - 2); 23 } 24 }; 25 26 int main(){ 27 long star,end,star_rec,end_rec; 28 Solution slt; 29 int n = 39; 30 int ans,ans_rec; 31 32 //循环实现 33 star = clock(); 34 ans = slt.Fibonacci(n); 35 end = clock(); 36 37 //递归实现 38 star_rec = clock(); 39 ans_rec = slt.Fibonacci_rec(n); 40 end_rec = clock(); 41 42 printf("%d , time_loop : %.15f\n", ans,(double)(end-star)/CLOCKS_PER_SEC); 43 printf("%d , time_recr : %.15f", ans_rec, (double)(end_rec - star_rec) / CLOCKS_PER_SEC); 44 return 0; 45 }