- Coin Change
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
my thoughts:
1. dp or bfs/dfs memory.
my solution:
**********
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if not coins or amount < 0:
return -1
if amount == 0:
return 0
dp = [amount + 1] * (amount + 1)
dp[0] = 0
coins.sort()
for i in range(1, amount + 1):
for c in coins:
if i - c < 0:
break
if dp[i - c] + 1 < dp[i]:
dp[i] = dp[i - c] + 1
return dp[-1] if dp[-1] < amount + 1 else -1
********** avoid recal like 2 + 3 + 5 and 3 + 5 + 2
class Solution:
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if not coins or amount < 0:
return -1
if amount == 0:
return 0
dp = [amount + 1] * (amount + 1)
dp[0] = 0
coins.sort()
for c in coins:
for i in range(c, amount + 1):
dp[i] = min(dp[i], dp[i - c] + 1)
return dp[-1] if dp[-1] < amount + 1 else -1
my comments:
from other ppl's solution:
1. Iterating over all combinations instead of all permutations!
int coinChange(vector<int>& coins, int amount)
vector<int> A(amount+1, amount+1);
A[0] = 0;
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
A[i] = min(A[i], A[i - coin] + 1);
}
}
return A[amount] > amount ? -1 : A[amount];
}