Coin Change
Given coin denominations coins and a target amount, return the fewest coins needed to make up exactly amount. You may use each denomination any number of times. Return -1 if the amount cannot be made (and 0 when amount is 0).
Implement coin_change(coins, amount).
Example
1,2,5 11
3
coinslists the denominations , and each one can be used as many times as you like.amountis the target, .- The output is a count of coins, not the coins themselves: the smallest such that denominations (repeats allowed) add up to exactly .
- Lower bound: even using only the biggest coin, , so two coins can never reach . At least are needed.
- Three coins do work: . Since is both reachable and a lower bound, the answer is
3. - Notice that reaching for the largest coin first is not reliable in general: with denominations and target , starting with forces (three coins), while needs only two.
- If no combination hits the target exactly (denominations , target : every sum is even), the answer is ; a target of needs coins.
Constraints
- 1 <= len(coins) <= 12
- 1 <= coins[i] <= 2^31 - 1
- 0 <= amount <= 10^4