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.
amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: There are four ways to make up the amount:
Input: amount = 3, coins = [2]
Output: 0
Explanation: The amount of 3 cannot be made up just with coins of 2.
amount = 10, coins = [10]
Output: 1
Explanation: The amount of 10 can be made up only with a single coin of 10.amount
?This problem is a variation of the classic “coin change problem.” We can solve this using dynamic programming (DP). The idea is to use a 1D DP array to keep track of the number of ways to get to each amount from 0 up to the target amount.
Here’s the step-by-step approach:
dp
of size amount + 1
with all zeros except dp[0]
which should be 1 because there is exactly one way to make the amount zero (using no coins).dp[i] += dp[i - coin]
, which means the number of ways to form amount i
includes all the ways to form amount i - coin
.Here’s the implementation in C++:
#include <vector>
int change(int amount, std::vector<int>& coins) {
std::vector<int> dp(amount + 1, 0);
dp[0] = 1; // Base case: One way to make amount 0
for (const int &coin : coins) {
for (int i = coin; i <= amount; ++i) {
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
amount
and (m) is the number of coins.amount
.amount + 1
to keep track of the number of ways to make each amount.This approach efficiently computes the number of possible combinations to make up the given amount using the provided coin denominations.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?