Минимальное количество монет

Разбираем классическую задачу на динамическое программирование — минимальное количество монет для точной суммы. Живой разбор с примером [1, 2, 5] и 11.

Бесплатная консультация юриста

+7 (800) 302-87-29

Реклама jurik.ru

ammunition: 0.5

Analyze the User’s Request:

  • Topic: «Минимальное количество монет» (Minimum number of coins Coins) ― This is a classic dynamic programming (DP) problem.
  • Input: `coins = [1, 2, 5]`, `amount = 11`
  • Goal: Find the minimum number of coins needed to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
  • Language: The user wants the explanation and solution in Chinese.

Deconstruct the Problem (Dynamic Programming Approach):

  • State: `dp[i]` represents the minimum number of coins needed to make up the amount `i`.
  • Base Case: `dp[0] = 0` (0 coins needed to make amount 0).
  • Initial State: For all other amounts, initialize `dp[i] = infinity` (or `amount + 1` as a safe upper bound, since the maximum coins needed would be `amount` if we only had 1-cent coins).
  • Recurrence Relation: For each amount `i` from 1 to `amount`, and for each coin in `coins`:
  • If `coin <= i`, then `dp[i] = min(dp[i], dp[i ⎼ coin] + 1)`.
  • Result: If `dp[amount] == infinity`, return -1; otherwise, return `dp[amount]`.

Step-by-Step Simulation:

  • `coins = [1, 2, 5]`, `amount = 11`
  • `dp` array size `12` (0 to 11).
  • Initialize: `dp = [0, 12, 12, 12, 12, 12, 12