Sunday, August 18, 2013

coin change

/* Given an infinite number of quarters (25 cents), dimes (10 cents), nickels (5 cents) and pennies (1 cent),
 write code to calculate the number of ways of representing n cents */

void subsetSum(int * coinArr, int coinChoices, int sum, int & ways) {
    if (sum == 0) {
        ways++;
        return;
    }
    if (coinChoices == 0 || sum < 0) {
        return;
    }
    // reaching sum that using the last kind of coin
    subsetSum(coinArr, coinChoices, sum-coinArr[coinChoices-1], ways);
    // reaching sum that not using the last kind of coin
    subsetSum(coinArr, coinChoices-1, sum, ways);
}

int calculateWays(int sum) {
    int ways = 0;
    int coinArr[] = {25, 10, 5, 1};
    int coinChoices = sizeof(coinArr) / sizeof(int);
    subsetSum(coinArr, coinChoices, sum, ways);
    return ways;

}

No comments:

Post a Comment