美文网首页
509. 斐波那契数

509. 斐波那契数

作者: 天山童姥张奶奶 | 来源:发表于2020-04-03 11:27 被阅读0次

    leetCode地址
    用Java写的
    递归

    class Solution {
        public int fib(int N) {
            if(N<=1) return N;
            return fib(N-1)+fib(N-2);
        }
    }
    

    非递归

    class Solution {
        public int fib(int N) {
            if(N<=1) return N;
            int first = 0;
            int second = 1;
            for(int i = 0;i < N-1; i ++){
                int sum = first + second;
                second += first;
                first = second - first;
    
            }
            return second;
        }
    }
    
    class Solution {
        public int fib(int N) {
            if(N<=1) return N;
            int first = 0;
            int second = 1;
            while (N --> 1){
                second += first;
                first = second - first;
            }
            return second;
        }
    }
    

    相关文章

      网友评论

          本文标题:509. 斐波那契数

          本文链接:https://www.haomeiwen.com/subject/hrbwmqtx.html