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())
}
}

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

被折叠的 条评论
为什么被折叠?



