Coin Change Minimum Coins DP

Bottom-up DP fills a table of least-coin counts for each amount, trying every denomination and returning None when the amount is unreachable.

RustData Integrity

Code

rustsnippet
26 lines
// dp[i] = 凑出金额 i 的最少硬币数;自底向上填表,
// 每个金额尝试每种面额取最小,凑不出则保持 None
fn min_coins(coins: &[u32], amount: u32) -> Option<usize> {
    let mut dp = vec![None; (amount + 1) as usize];
    dp[0] = Some(0);
    for i in 1..=amount as usize {
        for &coin in coins {
            let coin = coin as usize;
            if coin <= i {
                if let Some(prev) = dp[i - coin] {
                    let candidate = prev + 1;
                    if dp[i].map_or(true, |current| candidate < current) {
                        dp[i] = Some(candidate);
                    }
                }
            }
        }
    }
    dp[amount as usize]
}

fn main() {
    println!("{:?}", min_coins(&[1, 5, 12], 17)); // Some(2):12 + 5
    println!("{:?}", min_coins(&[2], 3)); // None:奇数金额凑不出
    println!("{:?}", min_coins(&[1, 2, 5], 11)); // Some(3):5 + 5 + 1
}

How it works

Coin Change Minimum Coins DP keeps everything in the functions min_coins and main.

for i in 1..=amount as usize is the loop that carries the per-item work.

What to watch for

  • All of its symbols are language built-ins — nothing needs fetching.

Putting it to use

The signature you will reach for first is fn min_coins(coins: &[u32], amount: u32) -> Option<usize>

Start the program and main runs min_coins one after another.

Core lines

let mut dp = vec![None; (amount + 1) as usize];
if let Some(prev) = dp[i - coin] {
    let candidate = prev + 1;
    if dp[i].map_or(true, |current| candidate < current) {
        dp[i] = Some(candidate);
    }
}
dp[0] = Some(0);

Interactive Tools for This Topic

FAQ

How do you run Coin Change Minimum Coins DP?
It runs as-is — treat the file as the whole program and execute it.