λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/leetcode

LeetCode 322 - Coin Change (Medium)

by HandHand 2021. 3. 3.

문제

LeetCode - 322번

풀이 κ³Όμ •

μ˜€λžœλ§Œμ— ν’€μ–΄λ³΄λŠ” 동적 κ³„νšλ²• λ¬Έμ œμž…λ‹ˆλ‹€.

dp[x] = x 원을 λ§Œλ“€κΈ° μœ„ν•œ μ΅œμ†Œ λ™μ „μ˜ 개수 라고 μ •μ˜ν•œλ‹€λ©΄ λ‹€μŒκ³Ό 같은 점화식을 얻을 수 μžˆμŠ΅λ‹ˆλ‹€.

dp[x] = for all coins, min{ dp[x - coins[i]] }


μ΄λ•Œ i λŠ” i 번째 동전을 μ˜λ―Έν•©λ‹ˆλ‹€.

μ½”λ“œ

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
var coinChange = function (coins, amount) {
  const dp = new Array(amount + 1).fill(Infinity);

  // μ΄ˆκΈ°κ°’
  dp[0] = 0;

  for (let money = 1; money <= amount; money++) {
    for (let i = 0; i < coins.length; i++) {
      if (coins[i] <= money) {
        dp[money] = Math.min(dp[money], dp[money - coins[i]] + 1);
      }
    }
  }

  const answer = dp[amount] === Infinity ? -1 : dp[amount];
  return answer;
};
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€