我目前正試圖在Python中實現動態編程,但我不知道如何設置回溯部分,以便它不重複排列。 例如,輸入爲(6,[1,5]),預期的輸出應爲2,因爲有兩種可能的方式來排列1和5,以使它們的和等於6.這些組合是{1, 1,1,1,1,1}和{1,5},但我的程序目前的工作方式,它說明了上面顯示的組合和組合{5,1}。這導致輸出爲3,這不是我想要的。所以我的問題是「我如何防止重複排列?」。我現在的代碼如下所示。蟒蛇幣更改動態編程
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
[Memoizing Coin Change]的可能重複(https://stackoverflow.com/questions/20742714/memoizing-coin-change) –