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
Rust DSA Implementation
basic.rs
fn list_string(values: &[i32]) -> String {
format!("[{}]", values.iter().map(|v| v.to_string()).collect::<Vec<_>>().join(", "))
}
fn main() {
let coins = [1, 3, 4];
let target = 6usize;
let inf = (target + 1) as i32;
let mut dp = vec![inf; target + 1];
dp[0] = 0;
for amount in 1..=target {
for coin in coins {
let coin = coin as usize;
if amount >= coin {
let candidate = dp[amount - coin] + 1;
if candidate < dp[amount] {
dp[amount] = candidate;
}
}
}
}
println!("{}", dp[target]);
println!("{}", list_string(&dp));
}
Output
2
[0, 1, 2, 1, 1, 2, 2]
Implementation notes
coinsis a fixed[i32; 3]array, whiletargetis6usizeso it can be used directly for vector lengths and indexes.let inf = (target + 1) as i32creates the unreachable sentinel7, andvec![inf; target + 1]initializesdp: Vec<i32>as[7, 7, 7, 7, 7, 7, 7]beforedp[0] = 0.- The outer loop scans amounts with
for amount in 1..=target; the inner loop copies each coin value and casts it withlet coin = coin as usizebefore indexingdp[amount - coin]. if amount >= coinguards the subtraction and vector access. The update is explicit:candidate = dp[amount - coin] + 1, then replacedp[amount]only whencandidate < dp[amount].- The fixed input always reaches every amount, so the source prints
dp[target]directly and does not convert the sentinel to a separate impossible value. - The trace shows
dpmoving from[0, 7, 7, 7, 7, 7, 7]through[0, 1, 2, 1, 1, 2, 2], with amount6choosingcoin 3 -> 2. println!("{}", dp[target])prints2, thenlist_string(&dp)borrows the table andprintln!("{}", ...)prints[0, 1, 2, 1, 1, 2, 2].