Coding Interview

[LeetCode] DFS, DP 322. Coin Change

milliwonkim 2022. 10. 4. 19:34
반응형
SMALL

문제

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

 

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

 

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

코드

Top Down(Memoization)

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function(coins, amount) {
    // coins에 있는 원소들을 이용해 더했을 때
    // amount를 만들 수 있는
    // 최소의 원소 갯수의 조합
    const memo = new Map();

    function dfs(left) {
        if(memo.has(left)) return memo.get(left);
        if(left === 0) return 0;
        let min = Infinity;
        for(let coin of coins) {
            if(left - coin >= 0) min = Math.min(min, dfs(left - coin));
        }

    // 예를들어, 모두 더해서 3이 나오는 최소 조합 = 1의 최소조합 + 2의 최소조합
    // 피보나치 수열처럼 구하기
        memo.set(left, min + 1)
        return min + 1
    }

    const result = dfs(amount);
    return result === Infinity ? -1 : result;
};

Bottom Up(Tabulation)

var coinChange = function(coins, amount) {
    const dp = Array(amount+1).fill(Infinity);
    dp[0] = 0;
    
    for(let i = 1; i < dp.length; i++) {
        for(let coin of coins) {
            if(i-coin >= 0) dp[i] = Math.min(dp[i], dp[i-coin]+1);
        }
    }
    return dp[amount] === Infinity ? -1 : dp[amount];
};
반응형
LIST