Coin Change(https://leetcode.com/problems/coin-change)
문제 설명
You are given an integer array
coinsrepresenting coins of different denominations and an integeramountrepresenting 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.
문제 해석
여러 종류의 동전을 나타내는 정수 배열 coins가 주어집니다. 또한, amount라는 총 금액이 주어집니다.
이 금액을 만들기 위해 필요한 최소 동전의 수를 반환하세요. 만약 이 금액을 주어진 동전으로 만들 수 없다면 -1을 반환하세요.
각 동전의 개수는 무한히 많다고 가정할 수 있습니다.
제한사항
- 1 <= coins.length <= 12
- 1 <= coins[i] <= 231 - 1
- 0 <= amount <= 104
입출력 예
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: -1
import java.util.*;
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
dp[0] = 0;
for (int i = 0; i < amount; i++) {
if (dp[i] == Integer.MAX_VALUE) continue;
for (int coin : coins) {
// Prevent overflow by checking if i + coin will overflow
if (coin > 0 && i <= amount - coin) {
dp[i + coin] = Math.min(dp[i + coin], dp[i] + 1);
}
}
}
return (dp[amount] == Integer.MAX_VALUE) ? -1 : dp[amount];
}
}