简体   繁体   中英

Coin Change Problem with Dynamic Programming

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.

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

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 .

    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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM