To solve the problem of finding the minimum number of coins needed to make a given amount using a set of coin denominations, we can use dynamic programming (DP). Here's a step-by-step approach:
Approach
The key idea is to use a DP array where dp[i] represents the minimum number of coins needed to make the amount i.
-
Initialization:
- Create a DP array of size
amount + 1filled with a large value (infinity) to indicate that initially, most amounts are unreachable. - Set
dp[0] = 0because zero coins are needed to make the amount 0.
- Create a DP array of size
-
DP Transition:
- For each amount from 1 to the target amount:
- For each coin denomination:
- If the coin is less than or equal to the current amount, update
dp[i]to the minimum of its current value ordp[i - coin] + 1(using the current coin to reach the amounti).
- For each amount from 1 to the target amount:
-
Result:
- If
dp[amount]remains infinity, return-1(the amount cannot be made with the given coins). Otherwise, returndp[amount].
- If
Solution Code
def coinChange(coins, amount):
if amount == 0:
return 0
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for coin in coins:
if coin <= i:
dp[i] = min(dp[i], dp[i - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
Explanation
- Initialization: The DP array starts with
inf(infinity) because we don't know the minimum coins for any amount except0(which is0). - Transition: For each amount
i, we check all coins. If a coin can be used (its value is ≤i), we see if using that coin (adding 1 to the count of coins needed fori - coin) gives a smaller number of coins than the current value ofdp[i]. - Result: After processing all amounts, if
dp[amount]is stillinf, it means the amount can't be formed with the given coins, so return-1. Otherwise, return the value atdp[amount].
This approach efficiently computes the minimum coins using dynamic programming with a time complexity of O(amount * number of coins) and space complexity of O(amount), which is optimal for this problem.
Example: For coins [1,2,5] and amount 11, the result is 3 (5+5+1). For coins [2] and amount 3, the result is -1 (unreachable). For coins [1] and amount 5, the result is 5.
This solution handles all edge cases and provides the correct result for any valid input.


作者声明:本文包含人工智能生成内容。