The Coin Change problem is stated as:
Given an integer array coins[ ] of size N representing different denominations of currency and an integer sum, find the number of ways you can make sum by using different combinations from coins[ ].
Note: Assume that you have an infinite supply of each type of coin.
So for example using coins {1, 2, 3} and a desired sums of 3, yields combinations (1,1,1), (1,2) and (3).
This problem can be solved using dynamic programming where the idea is to iteratively count the the number of combinations that can amount to a partial sum:
std::vector<int> combinations_to_consume_sum(sum + 1, 0);
combinations_to_consume_sum[0] = 1; // if we got here, we consumed everything using a single coin
for (int i = 0; i < N; ++i) // go through each coin
{
int coin = coins[i];
for (int partial_sum = 1; partial_sum <= sum; ++partial_sum)
{
int leftover_sum = partial_sum - coin;
if (leftover_sum >= 0)
{
combinations_to_consume_sum[partial_sum] += combinations_to_consume_sum[leftover_sum];
}
}
}
return combinations_to_consume_sum[sum];
This is a working solution. However, if I swap the order of the 2 nested loops, the algorithm is no longer correct:
for (int partial_sum = 1; partial_sum <= sum; ++partial_sum)
{
for (int i = 0; i < N; ++i)
{
int coin = coins[i];
int leftover_sum = partial_sum - coin;
if (leftover_sum >= 0)
{
combinations_to_consume_sum[partial_sum] += combinations_to_consume_sum[leftover_sum];
}
}
}
return combinations_to_consume_sum[sum];
Can someone offer an explanation as to why this approach only works when using a 'coins first' approach?
partial_sum
(in the first solution) at value 1, but then decide to do nothing untilpartial_sum>=coin
holds. You might as well start withpartial_sum=coin
. $\endgroup$