프로그래머스 Lv.2 숫자변환하기

Kim Jason·2023년 4월 3일
0

알고리즘 노트

목록 보기
28/35
post-thumbnail

💁🏻 코드

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 배열에 넣어주고 계속 따져주는 식으로 로직이 진행된다.

profile
성장지향형 프론트엔드 개발자

0개의 댓글