Reputation: 13
This is my code regarding the Coin Change Problem for print the total number of ways for a set of coins and the target amount
def coin_change(coins,amount):
table=[0 for k in range(amount+1)]
table[0]=1
for coin in coins:
for x in range(coin,amount+1):
table[x] = table[x]+ table[x-coin]
print(table)
return table[amount]
I want to know that is there any method to print those ways with the same dynamic programming solution (with the help of an inner constructed table or any other)
for example if a set of coins are [1,3,5] and target amount is 6 so there are total of 4 ways possible. [[1,1,1,1,1,1,],[1,1,1,3],[3,3],[1,5]] I want this way's list as an output.
Upvotes: 1
Views: 1143
Reputation: 7
Arrays.sort(coins);
int dp[]=new int [amount+1];
Arrays.fill(dp,amount+1);
dp[0]=0;
for(int i=0;i<=amount;i++){
for(int j=0;j<coins.length;j++){
if(coins[j]<=i){
dp[i]=Math.min(dp[i], 1+dp[i-coins[j]]);
}
else
break;
}
}
return dp[amount]>amount ? -1: dp[amount];
Upvotes: 0
Reputation: 5037
Answer edited per your requirement:
def combine(parent, me):
if len(parent) == 0:
return [[me]]
new_list = []
for entry in parent:
new_list.append(entry + [me])
return new_list
def get_ways(amount, coins):
table = [0 for k in range(amount + 1)]
table[0] = 1
ways = [[] for _ in range(amount + 1)]
for coin in coins:
for x in range(coin, amount + 1):
table[x] = table[x] + table[x - coin]
ways[x].extend(combine(ways[x - coin], coin))
print(ways[amount])
return table[amount]
print(get_ways(6, [1, 3, 5]))
The output:
[[1, 1, 1, 1, 1, 1], [1, 1, 1, 3], [3, 3], [1, 5]]
4
Upvotes: 1
Reputation: 104712
You can readily adapt your current code to produce a list solutions.
def coin_change(coins,amount):
table=[[] for k in range(amount+1)]
table[0].append([]) # or table[0] = [[]], if you prefer
for coin in coins:
for x in range(coin,amount+1):
table[x].extend(solution + [coin] for solution in table[x-coin])
print(table)
return table[amount]
The table
variable is now a list of lists of lists, with the inner lists being the combinations of coins that add up to a given value, rather than just a count of how many of those combinations there are. Instead of adding up the new combinations, I use a generator expression that we pass to extend
.
Upvotes: 0