-
문제
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제 해석
접근 방법
어떤 숫자를 다른 숫자로 변환하기 위해 드는 최소 연산 횟수를 계산합니다.
최소 연산 횟수를 찾기 위해 BFS 혹은 DP를 사용할 수 있습니다.
풀이 과정
1. BFS로 풀이 : 일부 시간 초과
function solution(x, y, n) { let [nx, cnt] = [x, 0]; const q = [[nx, cnt]]; while (q.length) { [nx, cnt] = q.shift(); if (nx === y) return cnt; cnt++; if (nx + n <= y) q.push([nx + n, cnt]); if (nx * 2 <= y) q.push([nx * 2, cnt]); if (nx * 3 <= y) q.push([nx * 3, cnt]); } return -1; }2. DP로 풀이 (최종 정답)
전체 코드
function solution(x, y, n) { const memo = new Array(y + 1).fill(-1); memo[x] = 0; while (x < y) { if (memo[x] > -1) { const arr = [x + n, x * 2, x * 3]; arr.forEach((a) => { if (a <= y) { memo[a] = memo[a] === -1 ? memo[x] + 1 : Math.min(memo[a], memo[x] + 1); } }); } x++; } return memo[y]; }회고
'Algorithm > JavaScript' 카테고리의 다른 글
[PRO] 프로그래머스 Lv.2 가장 큰 수 (Javascript) (1) 2024.11.12 [PRO] 프로그래머스 Lv.2 2개 이하로 다른 비트 (Javascript) (1) 2024.11.11 [PRO] 프로그래머스 Lv.2 타겟 넘버 (Javascript) (3) 2024.11.10 [PRO] 프로그래머스 Lv.2 땅따먹기 (Javascript) (0) 2024.11.09 [PRO] 프로그래머스 Lv.2 파일명 정렬 (Javascript) (2) 2024.11.08