我在stackoverflow Algorithm to find which number in a list sum up to a certain number
上找到了这个答案我正在努力学习动态编程,并认为遵循逻辑是一项挑战。我尝试将S == 0改为其他值但这并没有产生预期的结果。
是否可以修改此代码,以便数字不必与总数完全相加,即允许小的差异来处理舍入问题。
def f(v, i, S, memo):
if i >= len(v): return 1 if S == 0 else 0
if (i, S) not in memo: # <-- Check if value has not been calculated.
count = f(v, i + 1, S, memo)
count += f(v, i + 1, S - v[i], memo)
memo[(i, S)] = count # <-- Memoize calculated result.
return memo[(i, S)] # <-- Return memoized value.
def g(v, S, memo):
subset = []
for i, x in enumerate(v):
# Check if there is still a solution if we include v[i]
if f(v, i + 1, S - x, memo) > 0:
subset.append(x)
S -= x
return subset
v = [19783,21689,21169,11767,23207,12591]
sum = 56967
memo = dict()
if f(v, 0, sum, memo) == 0: print("There are no valid subsets.")
else: print(g(v, sum, memo))
返回[21169,23207,12591]
但是如果将21169更改为21168则返回“无有效子集”
v = [19783,21689,21168,11767,23207,12591]