...

/

Solution: The Coin Change Problem

Solution: The Coin Change Problem

Explore various approaches to solving the coin change problem in detail.

Solution 1: Brute force

using System;
class Program
{
/// <summary>
/// Finds the number of ways that the given number of cents can be represented.
/// </summary>
/// <param name="denoms">Values of the coins available.</param>
/// <param name="denomsLength">Number of denoms.</param>
/// <param name="amount">Given cent amount.</param>
/// <returns>The number of ways that the given number of cents can be represented.</returns>
public static int CountChange(int[] denoms, int denomsLength, int amount)
{
// If amount is 0 there is 1 solution
// (do not include any coin)
if (amount == 0)
{
return 1;
}
// If n is less than 0 then no
// solution exists
if (amount < 0 || denomsLength <= 0)
{
return 0;
}
// If there are no coins and n
// is greater than 0, then no
// solution exist
if (denomsLength <= 0 && amount >= 1)
{
return 0;
}
// Count is sum of solutions
// (i) including denoms[len(denoms) - 1]
// (ii) excluding denoms[len(denoms) - 1]
return CountChange(denoms, denomsLength - 1, amount) + CountChange(denoms, denomsLength, amount - denoms[denomsLength - 1]);
}
// Driver code to test the above function
public static void Main(string[] args)
{
int[] denoms = { 25, 10, 5, 1 };
Console.WriteLine(CountChange(denoms, denoms.Length, 10)); // Output: 4
}
}

Explanation

To count the total number of solutions, we divide the solution into two sets:

  • Solutions that do not contain the mthm^{th} denomination (or denoms[denomsLength - 1])
  • Solutions that contain at least one denoms[denomsLength - 1]

However, notice that the function recomputes the same subproblem several times (line 39).

Time complexity

The time complexity of this solution is in O(2denomslength)O(2^{denomslength}). Why? This is because, for every coin, we have two options: either include it or exclude it. If we think in terms of binary, it’s 0 to exclude and 1 to include. For example, if we have two coins, the options will be 00, 01, 10, 11, which is 4 or 222^2 ...