Coin Change
Problem
Given different coins of infinite amount, find the fewest coins to make up an amount.Solution
- DP.
- Can be done recursively or iteratively.
- Iterative code is much shorter.
- Top-down recursion: Start with amount and use one coin and find the min for the remaining recursively.
- Use memoization.
- Iterative: For 1 to amount find the min coin using min of (amount - coin_i) for each coin.
- Don't forget to initialize inf and 0 properly.
- For loops can be swapped!
# DP: Iterative
from typing import List
def coinChange(self, coins: List[int], amount: int) -> int:
import math
dp = [math.inf] * (amount + 1)
dp[0] = 0
for x in range(1, amount + 1):
for coin in coins:
if x >= coin:
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != math.inf else -1
# DP: Recursive:
def coinChange(self, coins: List[int], amount: int) -> int:
def minCoins(coins, rem, memoized):
if rem < 0:
return -1
if rem == 0:
return 0
if (rem-1) in memoized:
return memoized[rem-1]
tree_min = None
for coin in coins:
sub_tree_min = minCoins(coins, rem - coin, memoized)
if sub_tree_min >=0:
if not tree_min or sub_tree_min < tree_min:
tree_min = sub_tree_min + 1
memoized[rem-1] = tree_min if tree_min else -1
return memoized[rem-1]
if amount < 1:
return 0
memoized = {}
return minCoins(coins, amount, memoized)