본문 바로가기
코딩테스트 연습/DP

[백준] 1003번 피보나치 함수 (JavaScript)

by eddypark 2024. 4. 30.

https://www.acmicpc.net/problem/1003

const input = require('fs')
  .readFileSync(process.platform === 'linux' ? '/dev/stdin' : './input.txt')
  .toString()
  .trim()
  .split('\n')
  .map(Number);

let N = input[0];

let answer = [
  [1, 0],
  [0, 1],
];

for (let i = 1; i <= N; i++) {
  for (let j = 2; j <= input[i]; j++) {
    answer[j] = [
      answer[j - 1][0] + answer[j - 2][0],
      answer[j - 1][1] + answer[j - 2][1],
    ];
  }
  console.log(answer[input[i]].join(' '));
}

 

피보나치 함수 규칙에 따라서 0과 1이 나오는 횟수를 더 해주면 된다.