LeetCode每日一题(518. Coin Change 2)

该博客讨论了一种动态规划方法,用于计算给定不同面额硬币时达成特定金额的所有组合数。通过递归和缓存计算过程,可以避免重复计算并优化性能。示例展示了如何使用此算法解决特定的找零问题实例。

You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.

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

The answer is guaranteed to fit into a signed 32-bit integer.

Example 1:

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

Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1

Example 2:

Input: amount = 3, coins = [2]
Output: 0

Explanation: the amount of 3 cannot be made up just with coins of 2.

Example 3:

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

Constraints:

  • 1 <= coins.length <= 300
  • 1 <= coins[i] <= 5000
  • All the values of coins are unique.
  • 0 <= amount <= 5000

dp[amount][i] = dp[amount-coins[i] * 0][i+1] + dp[amount-coins[i]*1][i+1] + dp[amount-coins[i]*2][i+1], …, dp[amount-coins[i] * m][i+1], 其中 m = amount / coins[i]


use std::collections::HashMap;

impl Solution {
    fn dp(amount: i32, coins: &Vec<i32>, i: usize, cache: &mut HashMap<(i32, usize), i32>) -> i32 {
        if amount == 0 {
            return 1;
        }
        if i == coins.len() {
            return 0;
        }
        let curr = coins[i];
        let mut ans = 0;
        for m in 0..=amount / curr {
            let next_amount = amount - curr * m;
            let next = if let Some(c) = cache.get(&(next_amount, i + 1)) {
                *c
            } else {
                Solution::dp(next_amount, coins, i + 1, cache)
            };
            ans += next;
        }
        cache.insert((amount, i), ans);
        ans
    }
    pub fn change(amount: i32, coins: Vec<i32>) -> i32 {
        Solution::dp(amount, &coins, 0, &mut HashMap::new())
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值