Given an integer array coins representing coin denominations and an integer amount, return the fewest number of coins needed to make up that amount. Return -1 if impossible.
dp[i] = minimum coins to make amount i. For each amount, try every coin: if we use coin c, the remaining amount is i-c which we already know the answer to. So dp[i] = min(dp[i-c] + 1) for all valid coins c.
dp[0] = 0 (0 coins for amount 0). dp[1..amount] = Infinity initially (not yet reachable).
For each amount i from 1 to target: for each coin c where c ≤ i: dp[i] = min(dp[i], dp[i-c] + 1).
dp[amount] is the answer. If still Infinity, return -1.
Outer loop runs amount times, inner loop runs once per coin. dp array has amount+1 entries.
def coinChange(self, coins: List[int], amount: int) -> int:
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 -1What pattern do you think this problem uses?