找钱(Coin change)

  1. /// Coin change via Dynamic Programming
  2. /// coin_change(coins, amount) returns the fewest number of coins that need to make up that amount.
  3. /// If that amount of money cannot be made up by any combination of the coins, return `None`.
  4. ///
  5. /// Arguments:
  6. /// * `coins` - coins of different denominations
  7. /// * `amount` - a total amount of money be made up.
  8. /// Complexity
  9. /// - time complexity: O(amount * coins.length),
  10. /// - space complexity: O(amount),
  11. pub fn coin_change(coins: &[usize], amount: usize) -> Option<usize> {
  12. let mut dp = vec![std::usize::MAX; amount + 1];
  13. dp[0] = 0;
  14. // Assume dp[i] is the fewest number of coins making up amount i,
  15. // then for every coin in coins, dp[i] = min(dp[i - coin] + 1).
  16. for i in 0..=amount {
  17. for j in 0..coins.len() {
  18. if i >= coins[j] && dp[i - coins[j]] != std::usize::MAX {
  19. dp[i] = dp[i].min(dp[i - coins[j]] + 1);
  20. }
  21. }
  22. }
  23. match dp[amount] {
  24. std::usize::MAX => None,
  25. _ => Some(dp[amount]),
  26. }
  27. }
  28. #[cfg(test)]
  29. mod tests {
  30. use super::*;
  31. #[test]
  32. fn basic() {
  33. // 11 = 5 * 2 + 1 * 1
  34. let coins = vec![1, 2, 5];
  35. assert_eq!(Some(3), coin_change(&coins, 11));
  36. // 119 = 11 * 10 + 7 * 1 + 2 * 1
  37. let coins = vec![2, 3, 5, 7, 11];
  38. assert_eq!(Some(12), coin_change(&coins, 119));
  39. }
  40. #[test]
  41. fn coins_empty() {
  42. let coins = vec![];
  43. assert_eq!(None, coin_change(&coins, 1));
  44. }
  45. #[test]
  46. fn amount_zero() {
  47. let coins = vec![1, 2, 3];
  48. assert_eq!(Some(0), coin_change(&coins, 0));
  49. }
  50. #[test]
  51. fn fail_change() {
  52. // 3 can't be change by 2.
  53. let coins = vec![2];
  54. assert_eq!(None, coin_change(&coins, 3));
  55. let coins = vec![10, 20, 50, 100];
  56. assert_eq!(None, coin_change(&coins, 5));
  57. }
  58. }