The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
- 피보나치 수열 구현하기. N 이라는 숫자값이 주어지면 N 까지의 수열값 구하기
- N : 3 -> 0 + 1 + 1 = 2
/**
* @param {number} N
* @return {number}
*/
var fib = function fibonacciNumber(N) {
if(N <= 1) {
return N;
}
return fibonacciNumber(N-1) + fibonacciNumber(N-2);
};
/**
* @param {number} N
* @return {number}
*/
var fib = function fibonacciNumber(N, before = 0, after = 1, sum = 0) {
if(N === 0) return sum;
if(N === 1) return sum ? sum : 1;
sum = before + after;
return fibonacciNumber(N-1, before = after, after = sum, sum = sum);
};
피보나치를 재귀로 호출하는 경우에 함수 안에 함수를 계속해서 쌓아나가게 되기 때문에 (결국은 return되는 1의 합의 형태이므로, Fn을 호출하기 위해서 Fn개의 함수 스택이 쌓임) Maximum stack size exceed 에러가 터지기 쉽습니다. DP나 일반식으로 풀어보시는 것도 괜찮을 것 같네용