标签:斐波那契数列 blog ret pre span return code turn i++
递归:
int fib1(int n) { if(n<=0) return 0; if(n==1) return 1; return fib1(n-1)+fib1(n-2); }
非递归:
int fib2(int n) { int result[2] = {0,1}; if(n < 2) return result[n]; int fibOne = 0; int fibTwo = 1; int fibN = 0; int i = 0; for(i = 2; i <= n; i++) { fibN = fibOne + fibTwo; fibOne = fibTwo; fibTwo = fibN; } return fibN; }
时间复杂度为O(n)。
标签:斐波那契数列 blog ret pre span return code turn i++
原文地址:http://www.cnblogs.com/home123/p/6760853.html