프로그래머스 LEVEL 2(숫자 변환하기)
-
사용 언어 : javascript
-
해결 날짜 : 2023-01-30
-
해결 방법 :
- dp를 활용해 문제 해결
- x부터 시작해 n을 더한 값, 2 곱한 값, 3 곱한 값을(e) y와 비교하여
- e가 y와 같다면 현재 dp의 값 + 1 반환
- e의 dp값이 아직 없고 y보다 작다면 dp 업데이트 및 다음 반복문에 들어갈 data에 push
- data를 다 돌고도 찾지 못했다면 -1 반환
-
회고 :
- x
-
코드
function solution(x, y, n) { if (x === y) return 0; const dp = {}; dp[x] = 0; let data = [x]; while (data.length) { const nextData = []; for (const d of data) { for (const e of [d + n, 2 * d, 3 * d]) { if (e === y) { return dp[d] + 1; } else if (!dp[e] && e < y) { dp[e] = dp[d] + 1; nextData.push(e); } } } data = nextData; } return -1; }
-
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges