python换硬币_Python硬币更改动态编程

I am currently trying to implement dynamic programming in Python, but I don't know how to setup the backtracking portion so that it does not repeat permutations.

For example, an input would be (6, [1,5]) and the expected output should be 2 because there are 2 possible ways to arrange 1 and 5 so that their sum is equivalent to 6. Those combinations are {1,1,1,1,1,1} and {1,5} but the way my program currently works, it accounts for the combinations displayed above and the combination {5,1}. This causes the output to be 3 which is not what I wanted. So my question is "How do I prevent from repeating permutations?". My current code is shown below.

import collections as c

class DynamicProgram(object):

def __init__(self):

self.fib_memo = {}

# nested dictionary, collections.defaultdict works better than a regular nested dictionary

self.coin_change_memo = c.defaultdict(dict)

self.__dict__.update({x:k for x, k in locals().items() if x != 'self'})

def coin_change(self, n, coin_array):

# check cache

if n in self.coin_change_memo:

if len(coin_array) in self.coin_change_memo[n]:

return [n][len(coin_array)]

# base cases

if n < 0: return 0

elif n == 1 or n == 0: return 1

result = 0

i = 0

# backtracking (the backbone of how this function works)

while i <= n and i < len(coin_array):

result += self.coin_change(n-coin_array[i], coin_array)

i += 1

# append to cache

self.coin_change_memo[n][len(coin_array)] = result

# return result

return result

解决方案

One of the way of avoiding permutation is to use the numbers in "non-decreasing" order. By doing so you will never add answer for [5 1] because it is not in "non-decreasing" order.And [1 5] will be added as it is in "non-decreasing" order.

So the change in your code will be if you fix to use the ith number in sorted order than you will never ever use the number which is strictly lower than this.

The code change will be as described in Suparshva's answer with initial list of numbers sorted.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值