dp
of size amount + 1
and fill it with amount + 1
. This represents the minimum number of coins needed for each amount from 0 to amount
.dp[0]
to 0.amount
(inclusive), calling each value i
.i
, loop over each coin in coins
.i
, set dp[i]
to the minimum of dp[i]
and dp[i - coin] + 1
.dp
table, check if dp[amount]
is greater than amount
. If so, return -1.dp[amount]
.