内容中心

2026年靠谱的沙发源头工厂推荐-佛山市小牛家具有限公司

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.

  1. Initialization:

    • Create a DP array of size amount + 1 filled with a large value (infinity) to indicate that initially, most amounts are unreachable.
    • Set dp[0] = 0 because zero coins are needed to make the amount 0.
  2. 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 or dp[i - coin] + 1 (using the current coin to reach the amount i).
  3. Result:

    • If dp[amount] remains infinity, return -1 (the amount cannot be made with the given coins). Otherwise, return dp[amount].

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 except 0 (which is 0).
  • 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 for i - coin) gives a smaller number of coins than the current value of dp[i].
  • Result: After processing all amounts, if dp[amount] is still inf, it means the amount can't be formed with the given coins, so return -1. Otherwise, return the value at dp[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.

佛山市小牛家具有限公司

佛山市小牛家具有限公司



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

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?