Recursion and Dynamic Programming
Coin Change (Bottom-Up)
Build a one-dimensional table where each amount stores the fewest coins needed to make it.
Algorithm
Steps
- Initialize
dp[0] = 0and all other amounts to an unreachable sentinel. - Scan amounts from
1through6. - For each coin, read the earlier cell
dp[amount - coin]when it exists. - Write the smallest candidate into the current amount.
- Print both the final answer and the full DP array.
Complexity
- Time: O(target * coin_count)
- Space: O(target)
bottom-up dynamic programming
`dp[a]` is solved from already-computed smaller amounts, so every table cell has a visible dependency.
Visual walkthrough
Swift DSA Implementation
basic.swift
func listString(_ values: [Int]) -> String {
"[" + values.map(String.init).joined(separator: ", ") + "]"
}
let coins = [1, 3, 4]
let target = 6
let inf = target + 1
var dp = Array(repeating: inf, count: target + 1)
dp[0] = 0
for amount in 1...target {
for coin in coins {
if amount >= coin {
let candidate = dp[amount - coin] + 1
if candidate < dp[amount] {
dp[amount] = candidate
}
}
}
}
print(dp[target])
print(listString(dp))
Implementation notes
let coins = [1, 3, 4]andlet target = 6are immutable Swift[Int]andIntbindings for this replay.let inf = target + 1uses7as the unreachable sentinel; no valid answer for target6can need more than six1coins.var dp = Array(repeating: inf, count: target + 1)creates seven mutableIntcells for amounts0...6, thendp[0] = 0seeds the base amount.- The outer loop
for amount in 1...targetfills the table left to right, sodp[amount - coin]is already available whenamount >= coin. - The inner loop tries each coin and computes
let candidate = dp[amount - coin] + 1;dp[amount]changes only whencandidate < dp[amount]. - The trace shows the table moving from
[0, 7, 7, 7, 7, 7, 7]through amounts1and2, then using coin3fordp[3] = 1and coin4fordp[4] = 1. - For amount
6, coin3gives the best candidate2, leaving the final table[0, 1, 2, 1, 1, 2, 2]. print(dp[target])writes2, thenlistString(dp)prints the full table as[0, 1, 2, 1, 1, 2, 2].
Output
2
[0, 1, 2, 1, 1, 2, 2]