|
| 1 | +""" |
| 2 | +Problem Statement |
| 3 | +================= |
| 4 | +
|
| 5 | +Given a total and coins of certain denominations find number of ways total can be formed from coins assuming infinity |
| 6 | +supply of coins. |
| 7 | +
|
| 8 | +Analysis |
| 9 | +-------- |
| 10 | +* Runtime : O(num_of_coins * total) |
| 11 | +
|
| 12 | +Video |
| 13 | +----- |
| 14 | +* https://youtu.be/_fgjrs570YE |
| 15 | +
|
| 16 | +Reference |
| 17 | +--------- |
| 18 | +* http://www.geeksforgeeks.org/dynamic-programming-set-7-coin-change/ |
| 19 | +""" |
| 20 | + |
| 21 | + |
| 22 | +def coin_changing_num_ways(coins, total): |
| 23 | + cols = total + 1 # 1 for value 0 in total |
| 24 | + rows = len(coins) |
| 25 | + T = [[1 if col == 0 else 0 for col in range(cols)] for _ in range(rows)] |
| 26 | + |
| 27 | + for i in range(rows): |
| 28 | + for j in range(cols): |
| 29 | + if (i - 1) < 0: |
| 30 | + T[i][j] = 1 |
| 31 | + continue |
| 32 | + if j < coins[i]: |
| 33 | + T[i][j] = T[i - 1][j] |
| 34 | + else: |
| 35 | + T[i][j] = T[i - 1][j] + T[i][j - coins[i]] |
| 36 | + |
| 37 | + return T[rows - 1][cols - 1] |
| 38 | + |
| 39 | + |
| 40 | +def coin_changing_num_ways2(coins, total): |
| 41 | + cols = total + 1 |
| 42 | + num_coins = len(coins) |
| 43 | + |
| 44 | + # Using 1-D Array instead of 2-D Array. Approach is same as coin_changing_num_ways. |
| 45 | + T = [1 if col == 0 else 0 for col in range(cols)] |
| 46 | + |
| 47 | + for i in range(num_coins): |
| 48 | + for col in range(1, cols): |
| 49 | + if col >= coins[i]: |
| 50 | + T[col] += T[col - coins[i]] |
| 51 | + |
| 52 | + return T[cols - 1] |
| 53 | + |
| 54 | + |
| 55 | +def print_coin_changes_recursive(coins, total, results_stack, pos): |
| 56 | + if total == 0: |
| 57 | + for coin in results_stack: |
| 58 | + print "%d " % coin, |
| 59 | + print |
| 60 | + |
| 61 | + for idx in range(pos, len(coins)): |
| 62 | + if total >= coins[idx]: |
| 63 | + results_stack.append(coins[idx]) |
| 64 | + print_coin_changes_recursive(coins, total - coins[idx], results_stack, idx) |
| 65 | + results_stack.pop() # Remove last inserted coin from stack to use new coin with different index. |
| 66 | + |
| 67 | + |
| 68 | +def print_coin_changes(coins, total): |
| 69 | + print_coin_changes_recursive(coins, total, list(), 0) |
| 70 | + |
| 71 | + |
| 72 | +if __name__ == '__main__': |
| 73 | + coins = [1, 2, 3] |
| 74 | + total = 5 |
| 75 | + expected = 5 |
| 76 | + assert expected == coin_changing_num_ways(coins, total) |
| 77 | + assert expected == coin_changing_num_ways2(coins, total) |
| 78 | + print_coin_changes(coins, total) |
0 commit comments