아래와 같이 정의된 피보나치 수열 중 n번째 항의 수를 리턴해야 합니다.
let output = fibonacci(0);
console.log(output); // --> 0
output = fibonacci(1);
console.log(output); // --> 1
output = fibonacci(5);
console.log(output); // --> 5
output = fibonacci(9);
console.log(output); // --> 34
function fibonacci(n) {
// TODO: 여기에 코드를 작성합니다.
// 동적 계획법???
let newArr = [0, 1]; // 0번쨰와 1번째 요소는 고정시키기
let fib = (n) => { // 함수 1개 선언
if(newArr[n] !== undefined) {
return newArr[n]; // 기존꺼 리턴
}
newArr[n] = fib(n-1) + fib(n-2); // 새로운 합
return newArr[n]
}
return fib(n);
}
function fibonacci(n) {
if (n <= 1) {
return n;
};
return fibonacci(n-1) + fibonacci(n-2);
}
newArr
선언을 통해 0번째와 1번째를 고정시킨다는 것