Question

Possible Duplicate:
Making change recursively: How do I modify my algorithm to print all combinations?

In coin pattern counting problem(Given a value N and a fixed set of coins,we have to calculate the number of combinations of coins that would add up to N.), if we want to print the combinations rather counting the combinations, What is the approach ? Do I have to use dynamic programming for that ?

Was it helpful?

Solution

Yes, you need it. Assuming dp[i] equals the number of combinations that add up to i then the following pseudocode prints all combinations:

print_combinations(amount_left, current_coin):
    if amount_left == 0:
        print "\n"
        return
    if current_coin == num_coins:
        return
    if dp[amount_left - coins[current_coin]] > 0:
        print coins[current_coin], " "
        print_combinations(amount_left - coins[current_coin], current_coin)
    print_combinations(amount_left, current_coin + 1)

This function prints all the combinations of coins [current_coin .. last_coin] that add up to amount_left. So the initial call would be print_combinations(N, 0), as you can see the dynamic programming table dp[] helps us decide if we recurse using the current coin (we only recurse if there is at least one combination adding up to the new amount left which equals amount_left - coins[current_coin]).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top