Coin Change
Given a value N, find the number of ways to make change for N cents, if we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins. The order of coins doesn't matter.
Example:
Input:
N = 4
S = {1, 2, 3} //infinite number of 1 cent, 2 cent, 3 cent coins
Output:
4
{1,1,1,1} //four 1 cent coins
{1,1,2} //two 1 cent coins, one 2 cent coins
{2,2} //two 2 cent coins
{1,3} //one 1 cent and one 3 cent coins
Thus total four ways (Order doesn’t matter)
Let's think of the solution. Let’s do it by hand first. An intuitive idea can be two checks whether the amount can be handled by the same valued coins.
Like 4 cent can be managed by four 1 cent coins.
Same time can be managed by two 2 cent coins.
For the rest, we need to take different valued coins.
Now we can think of memorization. We can simply store the sub-amounts that can have been managed still.
Like two 1 cent coin manage 2 cents. Thus 2 cent is our sub amount.
Now we pick two more 1 cent coins that will sum up to 4.
Else we can pick only one 2cent coin also summing up to 4.
This memorized approach helps us to solve the problem.
Let's revise the algorithm
Pre-requisite: Coins array, amount
Algorithm:
Example with explanation:
This actually shows that by coin[1] all the sub-amounts can be managed only by one way, so if we continue this way for other coins we will get all the possible ways.
C++ implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer