알고리즘/LeetCode

[LeetCode] 518. Coin Change II - Java, JavaScript

반응형

https://leetcode.com/problems/coin-change-ii/description/

 

Coin Change II - LeetCode

Can you solve this real interview question? Coin Change II - You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the number of combinations that make up that

leetcode.com


문제

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

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

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

The answer is guaranteed to fit into a signed 32-bit integer.


풀이

풀이 과정

DP를 이용하여 0부터 amount원까지 각 금액을 만들 수 있는 경우의 수를 구해나간다.

우선 memoization을 위해 amount + 1길이 만큼의 배열을 선언하고 0번째 인덱스는 1로 초기화 한다.(0원을 만들 수 있는 경우의 수는 항상 1가지 이므로)

int[] dp = new int[amount + 1];
dp[0] = 1;

 

그리고 각 동전의 종류에 대해서 동전의 금액부터 amount까지 반복 탐색한다.
탐색하는 각 금액을 i라고 했을 때 i원이 될 수 있는 경우의 수는 i원에서 coin을 뺀 금액의 경우의 수와 같다고 할 수 있다.
그렇기 때문에 각 동전 별로 i - coin의 경우의 수를 i의 경우의 수에 합산하여 최종적으로 amount의 경우의 수를 return 한다.

for(int coin : coins) {
    for(int i = coin; i <= amount; i++) {
        // i원이 될 수 있는 경우의 수는
        // i원에서 coin만큼 뺀금액의 경우의 수
        // 따라서 i - coin의 경우의 수를 i의 경우의 수에 추가
        dp[i] += dp[i - coin];
    }
}

return dp[amount];

최종 코드

Java

class Solution {
    public int change(int amount, int[] coins) {
        int[] dp = new int[amount + 1];
        dp[0] = 1;
        
        for(int coin : coins) {
            for(int i = coin; i <= amount; i++) {
                // i원이 될 수 있는 경우의 수는
                // i원에서 coin만큼 뺀금액의 경우의 수
                // 따라서 i - coin의 경우의 수를 i의 경우의 수에 추가
                dp[i] += dp[i - coin];
            }
        }

        return dp[amount];
    }
}

 

JavaScript

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

  for (const coin of coins) {
    for (let i = coin; i <= amount; i++) {
      dp[i] += dp[i - coin];
    }
  }

  return dp[amount];
};