0

I've tried to solve a coin change problem in such a way that it'll compute the minimum numbers of coins that can be used. I've used the algorithm post on http://www.algorithmist.com. Here's the algorithm:

C(N,m) = min(C(N,m - 1),C(N - Sm,m) + 1)

with the base cases:

    C(N,m) = 1,N = 0
    C(N,m) = 0,N < 0
    C(N, m) = 0, N >= 1, m <= 0

But when I write the code it run to infinity.

Here's the code:

#include <iostream>
#include <algorithm>
using namespace std;
int Types[101];
int  Coins(int N, int m)
{
    if(N==0)
    {
        return 1;
    }
    else if(N<0)
    {
        return 0;
    }
    else if(N>0 && m<=0)
    {
        return 0;
    }
    else
    {
        int a = Coins(N,m-1);
        int b = Coins(N-Types[m],m) + 1;
        int c = min(a,b);
        return c;
    }
}

 int main()
{
    int noOfCoins, Target;
    cin >> noOfCoins >> Target;
    for(int i = 0; i<noOfCoins; i++)
    {
        cin >> Types[i];
    }
    cout << Coins(Target, noOfCoins);
    return 0;
}

What can be wrong?

Stefan4024
  • 694
  • 1
  • 10
  • 21
  • Also see [previous stackoverflow coin-changing problems](https://www.google.com/search?num=50&hl=en&q=site:stackoverflow.com/questions+coin+change+problem+-newest+-recently) – James Waldby - jwpat7 Mar 30 '13 at 16:25

1 Answers1

3

It should be cout << Coins(Target, noOfCoins - 1);

instead of cout << Coins(Target, noOfCoins);

Otherwise you are accessing a 0 element, and go to the same state again and again here:

int b = Coins(N-Types[m],m) + 1;

Petar Minchev
  • 46,889
  • 11
  • 103
  • 119
  • Good note. But I don't understand your point why I have to change in the 'int b' section, because if it's in the recursion, m can't go over the noOfCoins. Also I have found the the problem it's in the min part. If it returns 0, then the result will be definetly 0, so if a or b are 0, the I am excluding the 0. – Stefan4024 Mar 30 '13 at 15:00
  • You should change only this: `cout << Coins(Target, noOfCoins - 1);`. You don't have to change `int b` part. I was explaining that `N-0 = N` and you go to the same state. – Petar Minchev Mar 30 '13 at 15:01