我们采用递归的方式来求解这个动态规划问题
代码
1.样例输入代码
# max_weight=int(input())
# weight=input()
# weight = weight.split()
# weight = list(map(int, weight))# 使用 map() 函数和 int() 将子字符串列表转换为整数列表
# values_1=input()
# values_1 = values_1.split()
# values = list(map(int, values_1))
2.完整代码
##背包问题,动态规划,Recursion Solution--递归解法
# max_weight=int(input())
# weight=input()
# weight = weight.split()
# weight = list(map(int, weight))# 使用 map() 函数和 int() 将子字符串列表转换为整数列表
# values_1=input()
# values_1 = values_1.split()
# values = list(map(int, values_1))
weight=[1,2,4,2,5]
values=[5,3,5,3,2]
max_weight=10
# weight=[1,2,3]
# values=[2,4,3]
# max_weight=5
ans=0
if max_weight==0 or len(weight)==0:
print(0)
def Recursion(f,w_c):
if f>len(weight)-1:
return 0
if weight[f]>w_c:
ans=Recursion(f+1,w_c)
else:
ans=max(Recursion(f+1,w_c),Recursion(f+1,w_c-weight[f])+values[f])
return ans
print(Recursion(0,max_weight))