You are given an integer array coins
representing coins of different denominations and an integer amount
representing a total amount of money. Compute the number of ways to make up that amount using the given coins. You may assume that you have an infinite number of each kind of coin.
We can solve this problem using Dynamic Programming (DP). The idea is similar to the knapsack problem.
dp[i]
denote the number of ways to make up the amount i
using the given coins.dp[0] = 1
, because there is one way to make amount 0, which is to use no coins.coin
, update the dp array as follows:
for (int i = coin; i <= amount; i++) {
dp[i] += dp[i - coin];
}
Here’s a Java implementation of the described strategy:
public class Solution {
public int change(int amount, int[] coins) {
int[] dp = new int[amount + 1];
dp[0] = 1; // base case: one way to make amount 0
for (int coin : coins) {
for (int i = coin; i <= amount; i++) {
dp[i] += dp[i - coin];
}
}
return dp[amount];
}
}
n
is the number of coins and m
is the amount. This is because we iterate through each coin and for each coin, we update the dp array from the coin’s value up to the amount.m
is the amount, for storing the dp array.This approach ensures that we efficiently calculate the number of ways to make up the given amount using the provided coins.
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?