322. Coin Change

You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

 

Example 1:

Input: coins = [1,2,5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3
Output: -1

Example 3:

Input: coins = [1], amount = 0
Output: 0

Example 4:

Input: coins = [1], amount = 1
Output: 1

Example 5:

Input: coins = [1], amount = 2
Output: 2

 

Constraints:

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 231 - 1
  • 0 <= amount <= 104

Rust Solution

struct Solution;

impl Solution {
    fn coin_change(coins: Vec<i32>, amount: i32) -> i32 {
        let n = (amount + 1) as usize;
        let mut a = vec![-1; n];
        a[0] = 0;
        for i in 1..n {
            for &coin in &coins {
                if coin as usize <= i {
                    let j = i - coin as usize;
                    if a[j] != -1 {
                        if a[i] == -1 {
                            a[i] = a[j] + 1
                        } else {
                            a[i] = i32::min(a[i], a[j] + 1);
                        }
                    }
                }
            }
        }
        a[amount as usize]
    }
}

#[test]
fn test() {
    let coins = vec![1, 2, 5];
    let amount = 11;
    let res = 3;
    assert_eq!(Solution::coin_change(coins, amount), res);
    let coins = vec![2];
    let amount = 3;
    let res = -1;
    assert_eq!(Solution::coin_change(coins, amount), res);
}

Having problems with this solution? Click here to submit an issue on github.