[javascript] 피보나치 수열 (Fibonacci Sequence) 데이터 구조

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. It starts with 0 and 1, and the subsequent numbers are obtained by adding the last two numbers.

Recursive Approach

The Fibonacci sequence can be implemented in JavaScript using a recursive approach. Below is an example code:

function fibonacci(n) {
  if (n <= 1) {
    return n;
  } else {
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
}

// Example usage
console.log(fibonacci(10)); // Output: 55

This approach uses recursion to calculate the Fibonacci numbers. However, it can be inefficient for large values of n due to redundant calculations.

Dynamic Programming Approach

To optimize the Fibonacci sequence calculation, a dynamic programming approach can be used to store the results of subproblems and reuse them to avoid redundant calculations. Here’s an example code:

function fibonacciDynamic(n) {
  let fib = [];
  fib[0] = 0;
  fib[1] = 1;
  for (let i = 2; i <= n; i++) {
    fib[i] = fib[i - 1] + fib[i - 2];
  }
  return fib[n];
}

// Example usage
console.log(fibonacciDynamic(10)); // Output: 55

This approach uses an array to store the Fibonacci numbers and calculates each number iteratively.

By using the dynamic programming approach, the efficiency of the Fibonacci sequence calculation can be significantly improved, especially for large values of n.

References: