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
Lua DSA Implementation
basic.lua
local function list_string(values)
local parts = {}
for i, value in ipairs(values) do parts[i] = tostring(value) end
return "[" .. table.concat(parts, ", ") .. "]"
end
local coins = {1, 3, 4}
local target = 6
local inf = target + 1
local dp = {}
for i = 1, target + 1 do dp[i] = inf end
dp[1] = 0
for amount = 1, target do
for _, coin in ipairs(coins) do
if amount >= coin then
local candidate = dp[amount - coin + 1] + 1
if candidate < dp[amount + 1] then dp[amount + 1] = candidate end
end
end
end
print(dp[target + 1])
print(list_string(dp))
Implementation notes
- The pinned coins are
local coins = {1, 3, 4}and the target islocal target = 6. - Lua tables are 1-based in the list-style code here, so the source does not
store logical
dp[0]at numeric key0. - Instead, amount
0lives atdp[1], amount1lives atdp[2], and in general amountalives atdp[a + 1]. local inf = target + 1makes the unreachable sentinel7, larger than any possible coin count for this target.for i = 1, target + 1 do dp[i] = inf endfills seven table slots with7, thendp[1] = 0marks amount0as solved.- The trace starts from
[0, 7, 7, 7, 7, 7, 7]. - The outer loop is
for amount = 1, target do; the inner loop usesipairs(coins)to try coins1,3, then4in that order. - A coin is usable only when
amount >= coin. - The recurrence reads the offset earlier amount with
dp[amount - coin + 1] + 1and writes the current amount atdp[amount + 1]. - The trace updates the table to
[0, 1, 7, 7, 7, 7, 7]for amount1, then[0, 1, 2, 7, 7, 7, 7]for amount2. - Amount
3improves from coin3, giving[0, 1, 2, 1, 7, 7, 7]. - Amount
4improves from coin4, giving[0, 1, 2, 1, 1, 7, 7]. - Amounts
5and6finish as[0, 1, 2, 1, 1, 2, 7]and then[0, 1, 2, 1, 1, 2, 2]. - The final answer is read from
dp[target + 1], so target6prints2. list_string(dp)converts each table entry withtostringand joins them withtable.concat, producing[0, 1, 2, 1, 1, 2, 2].
Output
2
[0, 1, 2, 1, 1, 2, 2]