[백준9095_자바스크립트(javascript)] - 1, 2, 3 더하기

경이·2024년 10월 8일

𝑩𝑶𝑱 (𝒋𝒔)

목록 보기
209/325

🔴 문제

1, 2, 3 더하기


🟡 Sol

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

const dp = Array(12).fill(0);

dp[1] = 1;
dp[2] = 2;
dp[3] = 4;

for (let i = 4; i <= 12; i++) {
  dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
}

for (const input of inputs) {
  console.log(dp[input]);
}

🟢 풀이

⏰ 소요한 시간 : -

n1일 때는 1
n2일 때는 1 + 1, 2
n3일 때는 1 + 1 + 1, 2 + 1, 1 + 2, 3

이렇게 각각 1, 2, 4개의 방법이 있다. 따라서 해당 값으로 초기화를 해준다.

n4일 때는 n3일 때의 4가지 방법에 1을 더하는 경우와 n2일 때의 2가지 방법에 2를 더하는 경우와 n1일때의 1가지 방법에 3을 더하는 경우가 있다.
따라서 점화식은 다음과 같이 세워진다.

 dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]

🔵 Ref

profile
록타르오가르

0개의 댓글