本文内容为2022-2023学年第一学期运筹学课程动态规划部分的程序修改与讲解。
在课堂上展示的程序中,运行后可能会出现这样的结果:
memo = {}
def bestSum(targetSum, numbers):
shortest = None
## 终端条件
if targetSum == 0:
return []
if targetSum < 0:
return None
if memo.get(targetSum) is not None:
return memo.get(targetSum)
## 递归
## 状态转移
for number in numbers:
reminder = targetSum - number
reminder_r = bestSum(reminder,numbers)
if reminder_r is not None:
reminder_r.append(number)
if shortest is None or len(reminder_r) < len(shortest):
shortest = reminder_r.copy()
memo[targetSum] = shortest
return shortest
print(bestSum(100, [5, 4, 25]))