function solution(x, y, n) {
if (x === y) return 0;
const dp = {};
dp[x] = 0;
let check = [x];
while (check.length > 0) {
const newCheck = [];
for (const std of check) {
for (const tmp of [std + n, std * 2, std * 3]) {
if (dp[tmp] || tmp > y) continue;
if (tmp === y) return dp[std] + 1;
dp[tmp] = dp[std] + 1;
newCheck.push(tmp);
}
}
check = newCheck;
}
return -1;
}
완전탐색 방법도 생각해봤지만 동일한 값에 대한 계산 과정이 중복될 것 같아서 DP 알고리즘을 사용하기로 했다.
따져줘야 하는 수는 check 배열에 넣어주고 계속 따져주는 식으로 로직이 진행된다.