【Lintcode】斐波纳契数列

来源:互联网 发布:h3c配置vlan多个端口 编辑:程序博客网 时间:2024/05/17 23:11

非递归算法

class Solution { /** * @param n: an integer * @return an integer f(n) */ public int fibonacci(int n) { // write your code here if ( n == 1 ) { return 0; } else if ( n == 2 || n == 3 ) { return 1; } int s1 = 1; int s2 = 1; int i = 4; int sum = 0; while (i <= n) { sum = s1 + s2; s1 = s2; s2 = sum; i++; } return sum; }}

递归算法超过时间限制

public int fibonacci(int n) { // write your code here int a=0; int b=1; if(n==1)return a; if(n==2)return b; if(n>2)return fibonacci(n-1)+fibonacci(n-2); return 0; }


0 0
原创粉丝点击