斐波那契数列公式:
f(1)=1
f(2)=1
f(n )=f(n-1 ) f ) n-2 ) (n2 ) ) ) ) ) ) f(n )=f(n-1 ) f ) n-2 ) ) ) ) ) f ) n ) n ) n ) ) n ) n ) n ) n ) n ) n ) n ) n ) n ) n ) n ) n )
递归算法:时间复杂度o(2^n ) ) ) ) ) ) ) ) ) )的递归算法) ) ) ) ) ) )。
intrecursive_method(intn ) if ) n==1|||n==2) return 1; ELSEreturnrecursive_method(n-1 ) recursive _ method (n-2 ); }
非递归算法:时间复杂度o(n ) ) ) ) ) ) ) )的非递归算法:时间复杂度o(n ) ) ) ) ) )。
intnon_recursive_method(intn ) { int p=1; int q=1; int tmp; if(n==1||n==2)返回1; else{for(intI=3; i n; I ) ) { tmp=p; //本次周期的F(N-2 ) p=q; //p用于存储F(N-1 ),在下一个循环中f ) N-2 ) q=tmp q; //f(n )=f(n-1 ) f(n-2 ) }返回q; //q保存最新的f(n ) }