码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer:斐波那契数列

时间:2020-04-25 19:04:43      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:str   return   div   ++   off   color   turn   offer   strong   

1. 递归

过不了!超时!

 1 class Solution {
 2 public:
 3     int Fibonacci(int n) {
 4         if(n==0)
 5             return 0;
 6         if(n==1)
 7             return 1;
 8         if(n==2)
 9             return 1;
10         if(n>2)
11             return Fibonacci(n-1)+Fibonacci(n-2);
12     }    
13 };

2. 递归改循环

 1 class Solution {
 2 public:
 3     int Fibonacci(int n) {
 4         if(n==0)
 5             return 0;
 6         if(n==1)
 7             return 1;
 8         if(n==2)
 9             return 1;
10         int n1=1,n2=1,res;
11         for(int i=3;i<=n;i++)
12         {
13             res=n1+n2;
14             n1=n2;
15             n2=res;
16         }
17         return res;
18     }
19 };

 

剑指offer:斐波那契数列

标签:str   return   div   ++   off   color   turn   offer   strong   

原文地址:https://www.cnblogs.com/smartheadliu/p/12774291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!