Bestsum问题是经典的动态规划问题,它要求给定一个目标和数值target和一个非负整数数组arr,找出数组中的某些数字,它们的和等于target。Memoization是一种存储计算结果以供后续使用的优化技术,可以减少重复计算。因此,Bestsum问题可以使用Memoization来提高算法效率。
在Memoization版本中,我们定义一个记忆数组memo,来存储已经计算过的情况,以便后续直接使用,避免重复计算。记忆数组的大小为target+1,初始化为null。函数bestSum(target,arr,memo)表示当目标和为target时,使用数组arr中的数字,所得到的最小数字个数,如果无解则返回null。
代码如下:
def bestSum(target,arr,memo):
if target == 0:
return []
if target < 0:
return None
if memo[target] is not None:
return memo[target]
shortestCombination = None
for num in arr:
remainder = target - num
remainderCombination = bestSum(remainder,arr,memo)
if remainderCombination is not None:
combination = remainderCombination + [num]
if shortestCombination is None or len(combination) < len(shortestCombination):
shortestCombination = combination
memo[target] = shortestCombination
return shortestCombination
如果在运行这个函数时出现“Error in output in Bestsum Memoization problem”的错误,可能是memo数组的更新有问题。在代码中,我们在计算得到最短组合时,将其存储在memo数组,以便后续使用。因此,如果该组合为空,memo[target]应该存储None,而不是空数组[],这个问题可能会导致后续的计算出现问题。
修正方法是:
将memo[target] = shortestCombination 改为 memo[target] = None if shortestCombination is None else shortestCombination