dlehdanakf / Codingtest-Study

알고리즘 코딩테스트 토막지식 정리
1 stars 0 forks source link

DynamicProgramming, DP #1

Open dlehdanakf opened 3 years ago

dlehdanakf commented 3 years ago

개요

예제

피보나치 수열 구하기

const fibonacci = i => {
    if(i === 0) return 0;
    if(i === 1) return 1;
    return fibonacci(i - 1) + fibonacci(i - 2);
};
const DP = { };
const fibonacciDP = i => {
    if(i === 0) return 0;
    if(i === 1) return 1;
    if(DP[i] !== undefined) return DP[i];
    return DP[i] = fibonacciDP(i - 1) + fibonacciDP(i - 2);
};

n개의 계단을 오를 때 한 계단 씩, 또는 두 계단 씩, 최대 세 계단 씩 오를 수 있다.
계단을 오르는데 총 몇 가지 방법이 있는가?

const calcCount = n => {
    if(n < 0) {
        return 0;
    } else if(n === 0) {
        return 1;
    } else {
        return calcCount(n - 1) + calcCount(n - 2) + calcCount(n - 3);
    }
};
const DP = { 0: 1 };
const calcCountDP = n => {
    if(DP[n] !== undefined) {
        return DP[n];
    }

    if(n < 0) {
        return 0;
    } else {
        return DP[n] = calcCountDP(n - 1) + calcCountDP(n - 2) + calcCountDP(n - 3);
    }
};
dlehdanakf commented 3 years ago

프로그래머스 문제풀이

거스름돈

문제

푸는 방법

1 2 3 4 5
1 1 0 0 1
1 2 3 4 5
1 2 1 1 2
1 2 3 4 5
1 2 2 3 4
function solution(n, money) {
    const DP = new Array(n + 1).fill(0);
    money.forEach(i => {
        DP[i] += 1;
        for(let j = i + 1; j <= n; j++) {
            DP[j] += DP[j - i];
        }
    });

    return DP[n];
}
dlehdanakf commented 3 years ago

프로그래머스 문제풀이

멀리뛰기

문제

푸는 방법

function solution(n) {
    const DP = new Array(n + 1).fill(0);
    const up = n => {
        if(n === 1 || n === 0) return 1;
        if(n < 0) return 0;

        if(DP[n]) return DP[n];
        return DP[n] = (up(n - 1) + up(n - 2)) % 1234567;
    };

    return up(n);
}

거스름돈 문제와 무엇이 다른가?

function solution(n) {
    const jump = [1,2];
    const DP = new Array(n + 1).fill(0);
    const up = n => {
        if(n === 1 || n === 0) return 1;
        if(n < 0) return 0;

        if(DP[n]) return DP[n];
        return DP[n] = jump.reduce((acc, cur) => acc + up(n - cur), 0) % 1234567;
    };

    return up(n);
}
dlehdanakf commented 3 years ago

피보나치 수열

function solution(n) {
    if(n === 1) return 1;

    const DP = new Array(n + 1).fill(0);
    DP[0] = 0, DP[1] = 1;
    for(let i = 2; i <= n; i++) {
        DP[i] = (DP[i - 1] + DP[i - 2]) % 1234567;
    }

    return DP[n];
}