【剑指offer】10A--求裴波那切数列的第n项,C++实现
生活随笔
收集整理的這篇文章主要介紹了
【剑指offer】10A--求裴波那切数列的第n项,C++实现
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#本文是牛客網(wǎng)《劍指offer》刷題筆記
1.題目
????? 寫入一個(gè)函數(shù),輸入n,輸出裴波那切數(shù)列的第n項(xiàng)
?????
2.思路
- 遞歸--時(shí)間和空間復(fù)雜度高
- ?循環(huán)--時(shí)間和空間復(fù)雜度低,通過循環(huán)迭代計(jì)算第n項(xiàng),首先根據(jù)f(0)和f(1)計(jì)算f(2),在根據(jù)f(1)和f(2)計(jì)算f(3),依次類推計(jì)算出第n項(xiàng)。
3.code
1 class Solution { 2 public: 3 int Fibonacci(int n) { 4 // n==0 5 if(n<=0) 6 return 0; 7 8 // n==1 9 if(n==1) 10 return 1; 11 12 // n>1 13 int one=0; 14 int two=1; 15 int three=0; 16 17 for(int i = 2;i<=n;i++){ 18 three = one + two; 19 one =two; 20 two = three; 21 } 22 return three; 23 } 24 };?4.復(fù)雜度
? ? ? 時(shí)間復(fù)雜度O(n)
轉(zhuǎn)載于:https://www.cnblogs.com/wanglei5205/p/8522931.html
總結(jié)
以上是生活随笔為你收集整理的【剑指offer】10A--求裴波那切数列的第n项,C++实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: elementUI的table组件实现s
- 下一篇: java web入门——概念理解、名词解