内容中心

2026年知名的MGS通风软管厂家精选-陕西裕华永赫航宇科技有限公司

To solve this problem, we need to determine the number of ways to make change for a given amount using coins of denominations 1, 5, 10, and 25. This is a classic dynamic programming problem where we build up the solution by considering each coin denomination and updating the number of ways to form each amount up to the target value.

Approach

  1. Dynamic Programming (DP) Setup: We use a DP array dp where dp[i] represents the number of ways to make the amount i.
  2. Base Case: dp[0] = 1 because there is exactly one way to make the amount 0 (using no coins).
  3. Iterate Over Coins: For each coin denomination, update the DP array from the coin value up to the target amount. This ensures we count all combinations without double-counting (since we process each coin once and build up the solution incrementally).
  4. Update DP Array: For each amount j from the current coin value to the target, add the number of ways to make j - coin to dp[j] (since adding the current coin to those ways gives a new way to make j).

Solution Code

def count_change_ways(n):
    coins = [1, 5, 10, 25]
    dp = [0] * (n + 1)
    dp[0] = 1  # Base case: one way to make 0 amount

    for coin in coins:
        for j in range(coin, n + 1):
            dp[j] += dp[j - coin]

    return dp[n]

# Example usage:
# print(count_change_ways(5))  # Output: 2
# print(count_change_ways(10)) # Output: 4
# print(count_change_ways(15)) # Output: 6

Explanation

  • Base Case: dp[0] = 1 is essential because it allows us to start building the solution for larger amounts.
  • Coin Processing: By iterating over each coin and updating the DP array from the coin value upwards, we ensure that each combination is counted exactly once. For example, when processing the coin 5, we add the ways to make j-5 to dp[j], which includes all combinations that use the coin 5.
  • Efficiency: The time complexity is O(n * k) where n is the target amount and k is the number of coin denominations (4 here). This is efficient even for large values of n (e.g., up to 10,000) because the number of coins is small.

This approach correctly computes the number of combinations to make the desired amount using the given coin denominations. It is optimal and easy to understand, making it a standard solution for this type of problem.

陕西裕华永赫航宇科技有限公司

陕西裕华永赫航宇科技有限公司



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

在线客服

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