Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 8 期(2019-05-15):求斐波那契数前N项 #10

Open
wingmeng opened this issue May 15, 2019 · 3 comments
Open

第 8 期(2019-05-15):求斐波那契数前N项 #10

wingmeng opened this issue May 15, 2019 · 3 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 15, 2019

来源:面试题
难度:★★

封装一个函数,接收1个整数参数 n,返回 斐波那契数列 前 n 项

/**
 * @param {number} n - 整数
 */
function fibonacci(n) {
  // 你的代码
}

参考答案:

function fibonacci(n) {
  var a = 0;
  var b = 1;
  var c = a + b;
  var arr = [c];

  for (var i = arr.length; i < n; i++) {
    arr.push(c);
    a = b;
    b = c;
    c = a + b;
  }

  return arr;
}

// 再来个使用递归+ES6实现的(原创)
function fibonacci(n) {
  let fn = i => i < 3 ? 1 : fn(i - 1) + fn(i - 2);
  return [...Array(n).keys()].map(it => fn(it + 1));
}

本期优秀回答者: @AMY-Y

@liwenkang
Copy link

function getFibonacciArray(n) {
    let result = [];
    let map = new Map();
    map.set(1, 1);
    map.set(2, 1);

    function fibonacci(n) {
        if (map.get(n)) {
            return map.get(n);
        } else {
            let result = fibonacci(n - 2) + fibonacci(n - 1);
            map.set(n, result);
            return result;
        }
    }

    fibonacci(n);
    return map.values();
}

@AMY-Y
Copy link

AMY-Y commented May 15, 2019

function feibonacci(n){
            if(Math.round(n)===n){
                var arr=[];
                var sum1=1;
                var sum2=1;
                if(n==1){
                    arr.push(sum1);
                }else{
                    arr.push(sum1);
                    arr.push(sum2);
                    for(var i=2;i<n;i++){
                        var temp;
                        temp=sum1+sum2;
                        sum1=sum2;
                        sum2=temp;
                        arr.push(temp);
                    }
                }                
                return arr;
            }
        }
        feibonacci(8);

@ahao430
Copy link

ahao430 commented May 16, 2019

function fibonacci(n) {
  if (n < 0) return []

  let res = []
  for (let i = 0; i < n; i++) {
    let num
    if (i === 0) num = 0
    else if (i === 1) num = 1
    else num = res[i - 1] + res[i - 2]
    res.push(num)
  }
  return res
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants